package com.yeejoin.amos.boot.module.elevator.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.annotation.ResubmitCheck;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.elevator.api.dto.*;
import com.yeejoin.amos.boot.module.elevator.api.entity.Elevator;
import com.yeejoin.amos.boot.module.elevator.api.entity.EnterpriseInfo;
import com.yeejoin.amos.boot.module.elevator.api.entity.MaintenanceUnit;
import com.yeejoin.amos.boot.module.elevator.api.service.IEnterpriseInfoService;
import com.yeejoin.amos.boot.module.elevator.api.service.IMaintenanceUnitService;
import com.yeejoin.amos.boot.module.elevator.api.service.ITzBaseEnterpriseInfoService;
import com.yeejoin.amos.boot.module.elevator.biz.service.impl.ElevatorServiceImpl;
import com.yeejoin.amos.boot.module.elevator.biz.utils.BeanDtoVoUtils;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.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.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 维保单位Api
 *
 * @author tb
 * @date 2021-06-01
 */
@RestController
@Api(tags = "维保单位Api")
@RequestMapping(value = "/maintenance-unit")
public class MaintenanceUnitController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(MaintenanceUnitController.class);

    @Autowired
    IMaintenanceUnitService iMaintenanceUnitService;

    @Autowired
    IEnterpriseInfoService iEnterpriseInfoService;

    @Autowired
    ElevatorServiceImpl elevatorServiceImpl;

    /**
     * 新增维保单位
     *
     * @param maintenanceUnitDto 新增参数
     * @return 返回结果
     */
    @ResubmitCheck
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增维保单位", notes = "新增维保单位")
    public ResponseModel<Boolean> saveMaintenanceUnit(@RequestBody MaintenanceUnit maintenanceUnitDto) {
        MaintenanceUnit maintenanceUnit = BeanDtoVoUtils.convert(maintenanceUnitDto, MaintenanceUnit.class);
        boolean save = iMaintenanceUnitService.save(maintenanceUnit);
        return ResponseHelper.buildResponse(save);
    }

    /**
     * 根据id删除
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public ResponseModel<Boolean> deleteById(@PathVariable Long id) {
        boolean remove = iMaintenanceUnitService.removeById(id);
        return ResponseHelper.buildResponse(remove);
    }

    /**
     * 修改维保单位
     *
     * @param maintenanceUnitDto 修改参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "修改维保单位", notes = "修改维保单位")
    public ResponseModel<Boolean> updateByIdMaintenanceUnit(@RequestBody MaintenanceUnit maintenanceUnitDto) {
        MaintenanceUnit maintenanceUnit = BeanDtoVoUtils.convert(maintenanceUnitDto, MaintenanceUnit.class);
        boolean update = iMaintenanceUnitService.updateById(maintenanceUnit);
        return ResponseHelper.buildResponse(update);
    }

    /**
     * 根据id查询
     *
     * @param id id
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<MaintenanceUnitDto> selectById(@PathVariable Long id) {
        MaintenanceUnit maintenanceUnit = iMaintenanceUnitService.getById(id);
        MaintenanceUnitDto maintenanceUnitDto = BeanDtoVoUtils.convertMaintenanceUnitToVo(maintenanceUnit, false);
        return ResponseHelper.buildResponse(maintenanceUnitDto);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/ocp/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public ResponseModel<Map<String, Object>> selectMessage(@PathVariable String id) {
        Map<String, Object> objectMap = iMaintenanceUnitService.selectMessage(id);
        return ResponseHelper.buildResponse(objectMap);
    }
    /**
     * 列表分页查询
     *
     * @param pageNum            当前页
     * @param pageSize           每页大小
     * @param maintenanceUnitDto 查询参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<IPage<MaintenanceUnitDto>> listPage(String pageNum, String pageSize,
                                                            MaintenanceUnit maintenanceUnitDto) {
        MaintenanceUnit maintenanceUnit = BeanDtoVoUtils.convert(maintenanceUnitDto, MaintenanceUnit.class);
        Page<MaintenanceUnit> pageBean;
        QueryWrapper<MaintenanceUnit> maintenanceUnitQueryWrapper = new QueryWrapper<>();
        Class<? extends MaintenanceUnit> aClass = maintenanceUnit.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(maintenanceUnit);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(maintenanceUnit);
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(maintenanceUnit);
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(maintenanceUnit);
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(maintenanceUnit);
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        IPage<MaintenanceUnit> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iMaintenanceUnitService.page(pageBean, maintenanceUnitQueryWrapper);
        IPage<MaintenanceUnitDto> maintenanceUnitDtoIPage = BeanDtoVoUtils.maintenanceUnitIPageDto(page);
        return ResponseHelper.buildResponse(maintenanceUnitDtoIPage);
    }

    /**
     * 分页查询维保单位信息
     *
     * @param pageNum            当前页
     * @param pageSize           每页大小
     * @param maintenanceUnitDto 查询参数
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/query_maintenance_unit_list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "分页查询维保单位信息", notes = "分页查询维保单位信息")
    public ResponseModel<IPage<MaintenanceUnitDto>> queryMaintenanceUnitList(String pageNum, String pageSize,
                                                                            MaintenanceUnit maintenanceUnitDto) {
        MaintenanceUnit maintenanceUnit = BeanDtoVoUtils.convert(maintenanceUnitDto, MaintenanceUnit.class);
        Page<MaintenanceUnit> pageBean;
        QueryWrapper<MaintenanceUnit> maintenanceUnitQueryWrapper = new QueryWrapper<>();
        Class<? extends MaintenanceUnit> aClass = maintenanceUnit.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(maintenanceUnit);
                if (o != null) {
                    String name = NameUtils.camel2Underline(field.getName());
                    if ("city".equalsIgnoreCase(name) || "district".equalsIgnoreCase(name) || "qualification_level".equalsIgnoreCase(name)) {
                        String fileValue = (String) o;
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else if ("credit_level".equalsIgnoreCase(name)) {
                        Integer fileValue = (Integer) o;
                        maintenanceUnitQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) o;
                        maintenanceUnitQueryWrapper.like(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        IPage<MaintenanceUnit> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iMaintenanceUnitService.page(pageBean, maintenanceUnitQueryWrapper);
        IPage<MaintenanceUnitDto> maintenanceUnitDtoIPage = BeanDtoVoUtils.maintenanceUnitIPageDto(page);
        return ResponseHelper.buildResponse(maintenanceUnitDtoIPage);
    }

    /**
     * 分页查询维保单位/使用单位信息
     *
     * @param pageNum            当前页
     * @param pageSize           每页大小
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/query_agency_unit_list/ocp/{unitType}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "分页查询维保单位/使用单位信息", notes = "分页查询维保单位/使用单位信息")
    public ResponseModel<IPage<BaseEnterpriseInfoDto>> queryMaintenanceUnitList(String pageNum, String pageSize,
                                                                                @PathVariable(required = false) String unitType,
                                                                                EnterpriseInfo enterpriseInfoDto) {
        enterpriseInfoDto.setUnitType(unitType);
        EnterpriseInfo enterpriseInfo = BeanDtoVoUtils.convert(enterpriseInfoDto, EnterpriseInfo.class);
        Page<EnterpriseInfo> pageBean;
        QueryWrapper<EnterpriseInfo> enterpriseInfoQueryWrapper = new QueryWrapper<>();
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            throw new BadRequest("未指定人员归属单位信息");
        }
        String orgCode = companyModels.get(0).getOrgCode();
        if ("50*18667".equals(orgCode)) {
            enterpriseInfoQueryWrapper.likeRight("supervise_org_code","50*52").or().likeRight("supervise_org_code","50*73");
        } else {
            enterpriseInfoQueryWrapper.likeRight("supervise_org_code",orgCode);
        }

        Class<? extends EnterpriseInfo> aClass = enterpriseInfo.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(enterpriseInfo);
                if (o != null) {
                    String name = NameUtils.camel2Underline(field.getName());
                    if ("city".equalsIgnoreCase(name) ) {
                        String fileValue = (String) o;
                        enterpriseInfoQueryWrapper.eq(name, fileValue);
                    } else if ("credit_level".equalsIgnoreCase(name)) {
                        Integer fileValue = (Integer) o;
                        enterpriseInfoQueryWrapper.eq(name, fileValue);
                    } else if ("unit_type".equalsIgnoreCase(name)) {
                        // 1 维保单位，2 使用单位
                        String fileValue = (String) o;
                        if ("1".equals(fileValue)) {
                            // 此处由于写接口时表数据还未进行整理，所以此处先默认用文字做查询
                            enterpriseInfoQueryWrapper.like(name, "使用单位");
                        } else {
                            enterpriseInfoQueryWrapper.like(name, "安装改造维修单位");
                        }
                    } else {
                        String fileValue = (String) o;
                        enterpriseInfoQueryWrapper.like(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        IPage<EnterpriseInfo> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iEnterpriseInfoService.page(pageBean, enterpriseInfoQueryWrapper);
        IPage<BaseEnterpriseInfoDto> enterpriseInfoDtoIPage = BeanDtoVoUtils.enterpriseInfoIPageDto(page);
        return ResponseHelper.buildResponse(enterpriseInfoDtoIPage);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/ocp/exportData/{unitType}")
    @ApiOperation(httpMethod = "GET", value = "维保、使用单位列表导出", notes = "维保、使用单位列表导出")
    public void exportData(HttpServletResponse response, @PathVariable(required = false) String unitType,
                           EnterpriseInfo enterpriseInfoDto) {
        enterpriseInfoDto.setUnitType(unitType);
        EnterpriseInfo enterpriseInfo = BeanDtoVoUtils.convert(enterpriseInfoDto, EnterpriseInfo.class);
        QueryWrapper<EnterpriseInfo> enterpriseInfoQueryWrapper = new QueryWrapper<>();
        Class<? extends EnterpriseInfo> aClass = enterpriseInfo.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(enterpriseInfo);
                if (o != null) {
                    String name = NameUtils.camel2Underline(field.getName());
                    if ("city".equalsIgnoreCase(name) ) {
                        String fileValue = (String) o;
                        enterpriseInfoQueryWrapper.eq(name, fileValue);
                    } else if ("credit_level".equalsIgnoreCase(name)) {
                        Integer fileValue = (Integer) o;
                        enterpriseInfoQueryWrapper.eq(name, fileValue);
                    } else if ("unit_type".equalsIgnoreCase(name)) {
                        // 1 维保单位，2 使用单位
                        String fileValue = (String) o;
                        if ("1".equals(fileValue)) {
                            // 此处由于写接口时表数据还未进行整理，所以此处先默认用文字做查询
                            enterpriseInfoQueryWrapper.like(name, "使用单位");
                        } else {
                            enterpriseInfoQueryWrapper.like(name, "安装改造维修单位");
                        }
                    } else {
                        String fileValue = (String) o;
                        enterpriseInfoQueryWrapper.like(name, fileValue);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        if (!ObjectUtils.isEmpty(enterpriseInfoDto.getIds())){
            enterpriseInfoQueryWrapper.lambda().in(EnterpriseInfo :: getSequenceNbr, enterpriseInfo.getIds());
        }
        ArrayList<EnterpriseInfoExportDto> list = new ArrayList<>();
        List<EnterpriseInfo> enterpriseInfos = iEnterpriseInfoService.getBaseMapper().selectList(enterpriseInfoQueryWrapper);
        enterpriseInfos.forEach(item ->{
            EnterpriseInfoExportDto dto = new EnterpriseInfoExportDto();
            BeanUtils.copyProperties(item, dto);
            list.add(dto);
        });
        ExcelUtil.createTemplate(response, "单位信息", "单位信息", list, EnterpriseInfoExportDto.class, null, false);
    }
    /**
     * 根据名称查询维保单位列表
     *
     * @param unitName 维保单位名称
     * @return 返回结果
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/query_maintenance_unit_name_list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据名称查询维保单位列表", notes = "根据名称查询维保单位列表")
    public ResponseModel<IPage<MaintenanceUnitNameDto>> queryMaintenanceUnitListWithName(@PathVariable(required =
            false) String unitName) {
        QueryWrapper<EnterpriseInfo> enterpriseInfoQueryWrapper = new QueryWrapper<>();
        enterpriseInfoQueryWrapper.select("distinct sequence_nbr,use_unit").like(StringUtils.isNotEmpty(unitName),
                "use_unit", unitName).like("unit_type","安装改造维修单位");
        Page<EnterpriseInfo> pageBean = new Page<>(0, Long.MAX_VALUE);
        IPage<EnterpriseInfo> page = iEnterpriseInfoService.page(pageBean, enterpriseInfoQueryWrapper);
        IPage<MaintenanceUnitNameDto> maintenanceUnitVoIPage = BeanDtoVoUtils.iPageVoStream(page,
                MaintenanceUnitNameDto.class);
        return ResponseHelper.buildResponse(maintenanceUnitVoIPage);
    }

    /**
     * 根据警情id 查找设备维保单位信息
     * @param alertId
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/alert/{alertId}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据警情id 查找设备维保单位信息", notes = "根据警情id 查找设备维保单位信息")
    public ResponseModel<MaintenanceUnitDto> selectByAlertId(@PathVariable Long alertId) {
        // 获取根据警情获取电梯信息
        Map<String,Object> map  = elevatorServiceImpl.selectByAlertId(alertId);
        if (ObjectUtils.isEmpty(map)) {
            throw new BadRequest("设备未找到");
        }
        // 根据设备使用id 获取维保单位信息
        List<Map<String,Object>> list = elevatorServiceImpl.selectMtByAlertId(String.valueOf(map.get("sequenceNbr")));
        if (ObjectUtils.isEmpty(list)) {
            throw new BadRequest("维保单位未找到");
        }
        MaintenanceUnitDto maintenanceUnitVo = new MaintenanceUnitDto();
        maintenanceUnitVo.setUnitName(ObjectUtils.isEmpty(list.get(0).get("unitName")) ? null :String.valueOf(list.get(0).get("unitName")));
        maintenanceUnitVo.setAddress(ObjectUtils.isEmpty(list.get(0).get("address")) ? null :String.valueOf(list.get(0).get("address")));
        maintenanceUnitVo.setId(ObjectUtils.isEmpty(list.get(0).get("sequenceNbr")) ? null : String.valueOf(list.get(0).get("sequenceNbr")));
        maintenanceUnitVo.setSocialCreditCode(ObjectUtils.isEmpty(list.get(0).get("useCode")) ? null : String.valueOf(list.get(0).get("useCode")));
        List<DutyPersonDto> dutyPersonList = new ArrayList<DutyPersonDto>();
        DutyPersonDto principal = new DutyPersonDto();
        principal.setDeptName("主要负责人1");
        principal.setPhone(ObjectUtils.isEmpty(list.get(0).get("phone")) ? null :String.valueOf(list.get(0).get("phone")));
        principal.setUserId(null);
        principal.setUserName(ObjectUtils.isEmpty(list.get(0).get("userName")) ? null : String.valueOf(list.get(0).get("userName")));
        dutyPersonList.add(principal);
        DutyPersonDto manager = new DutyPersonDto();
        manager.setDeptName("主要负责人2");
//        manager.setPhone(list.size() == 2 ? String.valueOf(list.get(0).get("phone")) : null);
//        manager.setUserId(null);
//        manager.setUserName(list.size() == 2 ? String.valueOf(list.get(0).get("userName")) : null);
        dutyPersonList.add(manager);
        maintenanceUnitVo.setDutyPersonList(dutyPersonList);

        return ResponseHelper.buildResponse(maintenanceUnitVo);
    }

}

