package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.DealerReviewEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.MaintenanceTypeEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.AcceptanceDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.service.IMaintenanceService;
import com.yeejoin.amos.boot.module.hygf.api.dto.MaintenanceDto;
import com.yeejoin.amos.boot.module.hygf.api.util.DesUtil;
import com.yeejoin.amos.boot.module.hygf.api.util.MaintenanceUtil;
import com.yeejoin.amos.boot.module.standard.api.entity.PublicAgencyUser;
import com.yeejoin.amos.boot.module.standard.api.mapper.PublicAgencyUserMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import com.yeejoin.amos.feign.systemctl.model.SmsRecordModel;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;

import java.util.*;

/**
 * 运维人员服务实现类
 *
 * @author system_generator
 * @date 2024-03-11
 */
@Service
public class MaintenanceServiceImpl extends BaseService<MaintenanceDto,Maintenance,MaintenanceMapper> implements IMaintenanceService {

    @Autowired
    RegionalCompaniesMapper regionalCompaniesMapper;
    @Autowired
    private UnitInfoServiceImpl unitInfoService;
    @Autowired
    MaintenanceFileServiceImpl maintenanceFileServiceImpl;
    @Autowired
    MaintenanceFileMapper maintenanceFileMapper;
    @Autowired
    MaintenanceMapper maintenanceMapper;
    @Autowired
    PublicAgencyUserMapper publicAgencyUserMapper;
    @Autowired
    MaintenanceLogMapper maintenanceLogMapper;
    @Value("${dealer.appcode.manage}")
    private String appCodes;


    @Value("${dealer.amosDealerId}")
    private Long amosDealerId;


    @Value("${dealer.appcode.role}")
    private Long role;

    @Autowired
    RedisUtils redisUtil;
    private static final String regionRedis="app_region_redis_data";
    private static final Integer isSignAnAgreement = 1;
    private  static final  String SMSTEMPCODENO="SMS_HYGF_0003";
    private  static final  String SMSTEMPCODEYES="SMS_HYGF_0004";


    @Value("${amos.secret.key}")
    String secretKey;
    /**
     * 分页查询
     */
    public Page<MaintenanceDto> queryForMaintenancePage( int current,int size,String name, String maintenanceTypeCode,  String lockStatus, String reviewStatus,Long regionalCompaniesSeq, Long dealerId
    ,String maintenanceType,String maintenanceAreaAddress,String regionalCompaniesCode, String dealerCode)   {

        PageHelper.startPage(current,  size);
        List<MaintenanceDto> resultPage = maintenanceMapper.Maintenancepage( name,  maintenanceTypeCode,   lockStatus,  reviewStatus, regionalCompaniesSeq,  dealerId,maintenanceType,maintenanceAreaAddress,regionalCompaniesCode,dealerCode);
        PageInfo<MaintenanceDto> page = new PageInfo(resultPage);
        Page<MaintenanceDto> pagenew = new Page<MaintenanceDto>();
        pagenew.setCurrent(current);
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(size);
        pagenew.setRecords(page.getList());
        return pagenew;

    }

    /**
     * 列表查询 示例
     */
    public List<MaintenanceDto> queryList(
            String name, //运维人员类型
            String maintenanceType //运维人员类型code
    ){
        List<MaintenanceDto> lisda=  maintenanceMapper.queryList(
                 name, //运维人员类型
                 maintenanceType //运维人员类型cod
        );
     return lisda;
    }


    @Transactional
    public Maintenance saveMaintenance(Maintenance model ){

        //验证账号是否已存在
        Integer numm= maintenanceMapper.selectauthLogininfo(model.getTelephone(),model.getAdminLoginName());

        //验证手机号是否已注册
        Integer numz=   maintenanceMapper.selectMaintenance(model.getTelephone(),model.getAdminLoginName());

        if(numm>0||numz>0){
            throw new BadRequest("请检查，账号或号码，已存在！");
        }

        //审核状态
        model.setReviewStatus(MaintenanceUtil.SHZ);

        //培训状态
        model.setTrainingStatus(MaintenanceUtil.WPX);
        //是否锁定
        model.setLockStatus(MaintenanceUtil.OK);
        //签订协议
        model.setIsSignAnAgreement(MaintenanceUtil.WQD);
        //设置区域公司
        RegionalCompanies regionalCompanies= regionalCompaniesMapper.selectRegionName(model.getRegionalCompaniesSeq());
        model.setRegionalCompaniesCode(regionalCompanies!=null?regionalCompanies.getRegionalCompaniesCode():null);
        model.setRegionalCompaniesName(regionalCompanies!=null?regionalCompanies.getRegionalCompaniesName():null);
        //设置经销商
        UnitInfo unitInfo= unitInfoService.getById(model.getDealerId());
        model.setAmosDealerCode(unitInfo!=null?unitInfo.getAmosCompanyCode():null);
        model.setAmosDealerId(unitInfo!=null?unitInfo.getAmosCompanySeq():null);
        model.setDealerId(unitInfo!=null?unitInfo.getSequenceNbr():null);
        model.setDealerName(unitInfo!=null?unitInfo.getName():null);
        //运维区域 name
//        JSONArray regionName = getRegionName();
//        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
//        if(model.getMaintenanceAreaCode()!=null){
//            String ConsigneeRegion="";
//            List<Integer>  da=model.getMaintenanceAreaCode();
//            if(da!=null&&!da.isEmpty()){
//                for (int i = 0; i < da.size(); i++) {
//                    for (RegionModel re : list) {
//                        if (re.getRegionCode().equals(Integer.valueOf(da.get(i)))) {
//                            if(da.size()-1==i){
//                                ConsigneeRegion = ConsigneeRegion + re.getRegionName();
//                            }else{
//                                ConsigneeRegion = ConsigneeRegion + re.getRegionName() + "-";
//                            }
//                            break;
//                        }
//                    }
//                }
//                model.setMaintenanceArea(ConsigneeRegion);
//            }
//        }
        //设置常住地址
//        if(model.getPermanentAddressCode()!=null){
//            String ConsigneeRegion="";
//            List<Integer>  da=model.getPermanentAddressCode();
//            if(da!=null&&!da.isEmpty()){
//                for (int i = 0; i < da.size(); i++) {
//                    for (RegionModel re : list) {
//                        if (re.getRegionCode().equals(Integer.valueOf(da.get(i)))) {
//                            if(da.size()-1==i){
//                                ConsigneeRegion = ConsigneeRegion + re.getRegionName();
//                            }else{
//                                ConsigneeRegion = ConsigneeRegion + re.getRegionName() + "-";
//                            }
//                            break;
//                        }
//                    }
//                }
//                model.setPermanentAddressName(ConsigneeRegion);
//            }
//        }
        //存储std
        //新增人员基础信息表
        PublicAgencyUser publicAgencyUser=new PublicAgencyUser();
        publicAgencyUser.setRealName(model.getName());
        publicAgencyUser.setIdType(model.getIdType());
        publicAgencyUser.setIdNumber(model.getIdCard());
        publicAgencyUser.setAmosId(model.getAmosDealerId());
        publicAgencyUser.setAmosOrgCode(model.getAmosDealerCode());
        publicAgencyUser.setAmosUserId(model.getAmosUserId());
        publicAgencyUser.setAmosUserName(model.getAdminLoginName());
        publicAgencyUser.setPassword(DesUtil.encode(model.getAdminLoginPwd(), secretKey));
        publicAgencyUser.setRole(null);
        publicAgencyUser.setLockStatus("LOCK");
        publicAgencyUser.setLockTime(new Date());
        publicAgencyUser.setEmergencyTelephone(model.getTelephone());
        publicAgencyUser.setIdCardFront(model.getIdCardFront()!=null?JSON.toJSONString(model.getIdCardFront()):null);
        publicAgencyUser.setIdCardOpposite(model.getIdCardOpposite()!=null?JSON.toJSONString(model.getIdCardOpposite()):null);
        publicAgencyUserMapper.insert(publicAgencyUser);

        //保存运维人员
        model.setFoundationId(publicAgencyUser.getSequenceNbr());
        maintenanceMapper.insert(model);
        //保存证书
        if(model.getMaintenanceFiles()!=null){
            List<MaintenanceFile> maintenanceFiles=  model.getMaintenanceFiles();
            for (MaintenanceFile maintenanceFile : maintenanceFiles) {
                maintenanceFile.setMaintenanceId(model.getSequenceNbr());
            }
            maintenanceFileServiceImpl.saveBatch(maintenanceFiles);
        }




        return model;
    }

    public JSONArray getRegionName() {
        JSONArray jsonArray = new JSONArray();
        if (redisUtil.hasKey(regionRedis)) {
            jsonArray = JSONArray.parseArray(redisUtil.get(regionRedis).toString());
        } else {
            Collection<RegionModel> regionChild = new ArrayList<>();
            RegionModel regionModel1 = new RegionModel();
            regionChild.add(regionModel1);
            FeignClientResult<Collection<RegionModel>> collectionFeignClientResult = Systemctl.regionClient.queryForTreeParent(null);
            Collection<RegionModel> result = collectionFeignClientResult.getResult();
            for (RegionModel regionModel : result) {
                if (null != regionModel && null != regionModel.getChildren()) {
                    for (RegionModel child : regionModel.getChildren()) {
                        if (null != child && null != child.getChildren()) {
                            for (RegionModel childChild : child.getChildren()) {
                                jsonArray.add(childChild);
                            }
                            child.setChildren(regionChild);
                            jsonArray.add(child);
                        }
                    }
                    regionModel.setChildren(regionChild);
                    jsonArray.add(regionModel);
                }
            }

            redisUtil.set(regionRedis, jsonArray);
        }
        return jsonArray;
    }

    //详情
    public Map<String,Object>  selectOneById(Long sequenceNbr){
        MaintenanceDto maintenanceDto=    maintenanceMapper.selectOneById(sequenceNbr);

        maintenanceDto.setIdCardFrontList(maintenanceDto.getIdCardFront()!=null?JSONArray.parseArray(maintenanceDto.getIdCardFront()):null);
        maintenanceDto.setIdCardOppositeList(maintenanceDto.getIdCardFront()!=null?JSONArray.parseArray(maintenanceDto.getIdCardOpposite()):null);

        MaintenanceLog maintenanceLog = maintenanceLogMapper.selectOne(new QueryWrapper<MaintenanceLog>().lambda().eq(MaintenanceLog::getMaintenanceId, sequenceNbr));
        maintenanceDto.setNotes(maintenanceLog.getNotes());
        maintenanceDto.setOperator(maintenanceLog.getOperator());
        maintenanceDto.setOperationTime(maintenanceLog.getOperationTime());

        //获取文档
      List<MaintenanceFile>   list=  maintenanceFileMapper.selectList(
                new QueryWrapper<MaintenanceFile>().lambda().eq(MaintenanceFile::getMaintenanceId, sequenceNbr)
      );
        maintenanceDto.setMaintenanceFiles(list);
      Map<String,Object>  jsonObject= BeanUtil.beanToMap(maintenanceDto);
       if(list!=null&&!list.isEmpty()){
           for (MaintenanceFile maintenanceFile : list) {
               jsonObject.put(maintenanceFile.getFileKey(),maintenanceFile.getFileUrl());
               jsonObject.put(maintenanceFile.getFileKey()+"effectiveDateEnd",maintenanceFile.getEffectiveDateEnd());
               jsonObject.put(maintenanceFile.getFileKey()+"effectiveDateStart",maintenanceFile.getEffectiveDateStart());
           }
       }
        return jsonObject;
    }

    @Transactional
    public Maintenance examine(Long sequenceNbr, MaintenanceLog maintenanceLog) {


        //保存操作日志
        maintenanceLog.setMaintenanceId(sequenceNbr);
        maintenanceLogMapper.insert(maintenanceLog);
        //判断审核状态
        Maintenance maintenance = maintenanceMapper.selectById(sequenceNbr);
        MaintenanceDto maintenanceDto = maintenanceMapper.selectOneById(sequenceNbr);

        if (maintenanceLog.getOperationResults().equals(MaintenanceUtil.BH)) {
            maintenance.setReviewStatus(MaintenanceUtil.BH);
            maintenanceMapper.updateById(maintenance);

            HashMap<String, String> params = new HashMap<>(3);
            params.put("code","不通过");
            params.put("mobile",maintenanceDto.getTelephone());
            params.put("smsCode", SMSTEMPCODENO);
            FeignClientResult<SmsRecordModel> date= Systemctl.smsClient.sendCommonSms(params);




            return maintenance;
        } else {
            //如果通过添加平台账号
            maintenance.setReviewStatus(MaintenanceUtil.TG);

            FeignClientResult<AgencyUserModel> userResult = null;
            //新增平台用户
            try {
                // 1 创建平台用户
                List<RoleModel> userRoleList = new ArrayList<>();
                AgencyUserModel agencyUserModel = new AgencyUserModel();
                agencyUserModel.setUserName(maintenanceDto.getAdminLoginName());
                agencyUserModel.setRealName(maintenanceDto.getName());
                agencyUserModel.setLockStatus("UNLOCK");
                agencyUserModel.setPassword(maintenanceDto.getAdminLoginPwd());
                agencyUserModel.setRePassword(maintenanceDto.getAdminLoginPwd());
                agencyUserModel.setAgencyCode("JXIOP");
                agencyUserModel.setMobile(maintenanceDto.getTelephone());
                List<String> split = Arrays.asList(StringUtils.split(appCodes, ','));
                Map<Long, List<Long>> roleSeqMap = new HashMap<>();
                Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
                List<Long> roleIds = new ArrayList<>();
                roleIds.add(role);

                if(maintenanceDto.getMaintenanceTypeCode().equals(MaintenanceTypeEnum.社会人员运维.getCode())){
                    roleSeqMap.put(amosDealerId, roleIds);
                    orgRoles.put(amosDealerId, userRoleList);

                }else{
                    roleSeqMap.put(Long.valueOf(maintenanceDto.getAmosDealerId()), roleIds);
                    orgRoles.put(Long.valueOf(maintenanceDto.getAmosDealerId()), userRoleList);

                }
                agencyUserModel.setOrgRoles(orgRoles);
                agencyUserModel.setOrgRoleSeqs(roleSeqMap);
                // 将创建用户加入用户组
                userResult = Privilege.agencyUserClient.create(agencyUserModel);
                if (userResult == null || userResult.getStatus() != 200) {
                    throw new BadRequest("新增人员失败！" + userResult.getDevMessage());
                }
                List<String> userId = new ArrayList<>();
                userId.add(userResult.getResult().getUserId());
                for (Long aLong : roleIds) {
                    Privilege.groupUserClient.create(aLong, userId);
                }
                //修改基础表
                PublicAgencyUser publicAgencyUser = publicAgencyUserMapper.selectById(maintenance.getFoundationId());
                //新增人员基础信息表
                publicAgencyUser.setAmosUserId(userResult.getResult().getUserId());
                publicAgencyUser.setLockStatus("UNLOCK");
                publicAgencyUser.setLockTime(new Date());
                publicAgencyUser.setRole(JSON.toJSONString(roleIds));
                publicAgencyUserMapper.updateById(publicAgencyUser);
                maintenanceMapper.updateById(maintenance);

                HashMap<String, String> params = new HashMap<>(3);
                params.put("code","通过");
                params.put("mobile",maintenanceDto.getTelephone());
                params.put("smsCode", SMSTEMPCODEYES);
                FeignClientResult<SmsRecordModel> date= Systemctl.smsClient.sendCommonSms(params);

                return maintenance;
            } catch (Exception e) {
                if (userResult != null && userResult.getResult() != null
                        && StringUtils.isNotEmpty(userResult.getResult().getUserId())) {
                    Privilege.agencyUserClient.multDeleteUser(userResult.getResult().getUserId());
                }
                log.error(e.getMessage(), e);
                throw new BadRequest(e.getMessage());
            }

        }

    }


   public void updateTraining(String userId){
        this.getBaseMapper().updateTraining(userId);
   }

   public void updateTrainingAgreement(String userId){
        this.getBaseMapper().updateTrainingAgreement(userId);
   }




    @Transactional
    public void updateUser( Long sequenceNbr , String type){

        FeignClientResult<List<String>>  userResult =null;
        MaintenanceDto maintenanceDto=    maintenanceMapper.selectOneById(sequenceNbr);

        PublicAgencyUser publicAgencyUser = publicAgencyUserMapper.selectById(maintenanceDto.getFoundationId());

        if("LOCK".equals(type)){
            userResult =   Privilege.agencyUserClient.lockUsers(publicAgencyUser.getAmosUserId());

            publicAgencyUser.setLockStatus("LOCK");
        }else{
            userResult = Privilege.agencyUserClient.unlockUsers(publicAgencyUser.getAmosUserId());
            publicAgencyUser.setLockStatus("UNLOCK");
        }
        publicAgencyUser.setLockTime(new Date());

        publicAgencyUserMapper.updateById(publicAgencyUser);
    }
}