package com.fufan.mtsaas.modules.base.company.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fufan.mtsaas.config.RedissonCommand;
import com.fufan.mtsaas.constant.RedisKeyConstant;
import com.fufan.mtsaas.exception.ExceptionHandle;
import com.fufan.mtsaas.modules.base.company.bo.request.CompanyQueryRequest;
import com.fufan.mtsaas.modules.base.company.bo.request.CompanySaveRequest;
import com.fufan.mtsaas.modules.base.company.bo.request.back.CompanyBackQueryRequest;
import com.fufan.mtsaas.modules.base.company.bo.request.back.CompanyBackSaveRequest;
import com.fufan.mtsaas.modules.base.company.bo.request.back.CompanyPurchaseSaveRequest;
import com.fufan.mtsaas.modules.base.company.bo.response.CompanyDataResponse;
import com.fufan.mtsaas.modules.base.company.bo.response.CompanyResponse;
import com.fufan.mtsaas.modules.base.company.bo.response.back.CompanyBackQueryResponse;
import com.fufan.mtsaas.modules.base.company.bo.response.back.CompanyPurchaseResponse;
import com.fufan.mtsaas.modules.base.company.dao.TCompanyContactDao;
import com.fufan.mtsaas.modules.base.company.dao.TCompanyDao;
import com.fufan.mtsaas.modules.base.company.dao.TCompanyPurchaseDao;
import com.fufan.mtsaas.modules.base.company.model.TCompany;
import com.fufan.mtsaas.modules.base.company.model.TCompanyContact;
import com.fufan.mtsaas.modules.base.company.model.TCompanyPurchase;
import com.fufan.mtsaas.modules.base.company.service.TCompanySvc;
import com.fufan.mtsaas.modules.base.log.bo.request.LogSaveRequest;
import com.fufan.mtsaas.modules.base.log.service.TSysLogSvc;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.modules.sysmgr.syuser.dao.SYuserDao;
import com.fufan.mtsaas.modules.sysmgr.syuser.model.SYuser;
import com.fufan.mtsaas.tools.AESTool;
import com.fufan.mtsaas.tools.MapTools;
import com.fufan.mtsaas.util.DataChangeUtil;
import com.fufan.mtsaas.util.DateFormatTool;
import com.fufan.mtsaas.util.ParamUtil;
import com.github.pagehelper.ISelect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * <p>
 * 企业信息表 服务实现类
 * </p>
 *
 * @author Liby
 * @since 2022-03-16
 */
@Service("TCompanySvcImpl")
@Slf4j
@Primary
public class TCompanySvcImpl extends ServiceImpl<TCompanyDao, TCompany> implements TCompanySvc {
    @Autowired
    private TCompanyDao entitymDao;
    @Autowired
    private TCompanyContactDao entityContactDao;
    @Autowired
    private TCompanyPurchaseDao tCompanyPurchaseDao;
    @Autowired
    private SYuserDao sYuserDao;
    @Autowired
    private RedissonCommand redissonCommand;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private TSysLogSvc tSysLogSvc;
    @Value("${COMPANY_ID}")
    private String COMPANY_ID;

    public static void main(String[] args) throws Exception {
        System.out.println(AESTool.encrypt("13333333333"));
    }

    @Override
    public Result doQueryPage(CompanyQueryRequest map, RequestPojo requestPojo) {
        log.info("TCompanySvcImpl doQueryPage {} ", map);
        Result result = new Result();
        //分页查询企业信息表
        Page page = new Page();
        List<CompanyResponse> entitys = null;

        Map<String, String> mapData = new HashMap<>();
        mapData.put("CompanyID", requestPojo.getCustId());
        mapData.put("CompanyName", map.getCompanyName());
        mapData.put("LegalName", map.getLegalName());
        mapData.put("UniformSocialCreditCode", map.getUniformSocialCreditCode());

        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                entitymDao.selectList(page, mapData);
            }
        });
        ParamUtil.setPage(map.getPageSize(), map.getCurrentPage(), page);
        entitys = entitymDao.selectList(page, mapData);
        for (CompanyResponse companyResponse : entitys) {
            companyResponse.setCreateBy(null);
            companyResponse.setCreateTime(null);
            companyResponse.setUpdateBy(null);
            companyResponse.setUpdateTime(null);
        }
        List<CompanyDataResponse> companyDataResponseList = DataChangeUtil.getDataList(entitys, CompanyDataResponse.class);
        for (CompanyResponse companyResponse : entitys) {
            for (CompanyDataResponse companyDataResponse : companyDataResponseList) {

                if (companyDataResponse.getId().equals(companyResponse.getId())) {
                    if (companyResponse.getIssueDate() != null) {
                        companyDataResponse.setIssueDate(companyResponse.getIssueDate());
                    }
                    if (companyResponse.getProductionExpiryDate() != null) {
                        companyDataResponse.setProductionExpiryDate(companyResponse.getProductionExpiryDate());
                    }
                    try {
                        if(StringUtils.isNotEmpty(companyDataResponse.getContactMobile())){
                            companyDataResponse.setContactMobile(AESTool.decrypt(companyDataResponse.getContactMobile()));
                        }
                        if(StringUtils.isNotEmpty(companyDataResponse.getContactTelephone())){
                            companyDataResponse.setContactTelephone(AESTool.decrypt(companyDataResponse.getContactTelephone()));
                        }
                    }catch (Exception e){

                    }
                }
            }
        }
        page.setTotal((int) total);

        page.setRecords(companyDataResponseList);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    /**
     * 新增
     *
     * @param map
     * @param requestPojo
     * @return Result.class
     */
    @Override
    @Transactional
    public Result doSave(CompanyBackSaveRequest map, RequestPojo requestPojo) {

        log.debug("TCompanySvcImpl.doSave parameter: {}", map);
        Result result = new Result();
        if(!requestPojo.getCustId().equals(COMPANY_ID)){
            result.setResStatus(ResStatus.STATUS_NOT_VJ_ERROR);
            result.setResMsg(ResStatus.STATUS_NOT_VJ_ERROR_MSG);
            return result;
        }
        TCompany entityData = new TCompany();
        BeanUtils.copyProperties(map, entityData);
        entityData.setIsEnabled(0);
        entityData.setCreateBy(requestPojo.getUserName());
        entityData.setCreateTime(new Date());
        entityData.setUpdateBy(requestPojo.getUserName());
        entityData.setUpdateTime(new Date());
        entityData.setRemark(map.getRemark());
        Map<String, String> purchaseMap = new HashMap<>();
        if (map.getCompanyPurchaseSaveRequestList() != null && map.getCompanyPurchaseSaveRequestList().size() > 0) {
            for (CompanyPurchaseSaveRequest companyPurchaseSaveRequest : map.getCompanyPurchaseSaveRequestList()) {
                if (purchaseMap.containsKey(companyPurchaseSaveRequest.getPurchaseContractNo())) {
                    result.setResStatus(ResStatus.STATUS_CONTRACT_NO_EXIT);
                    result.setResMsg(ResStatus.STATUS_CONTRACT_NO_EXIT_MSG);
                    return result;
                }
                purchaseMap.put(companyPurchaseSaveRequest.getPurchaseContractNo(), companyPurchaseSaveRequest.getPurchaseContractNo());
            }
        }
        try {
            int rec = 0;
            try {
                rec = entitymDao.insertRecords(entityData);
            } catch (Exception e) {
                if (ExceptionHandle.isDoubleKey(e)) {
                    result.setResStatus(ResStatus.STATUS_COMPANY_NO_DOUBLE);
                    result.setResMsg(ResStatus.STATUS_COMPANY_NO_DOUBLE_MSG);
                    return result;
                }
                log.error("公司更新失败" + e.getMessage());
            }
            if (rec <= 0) {
                result.setResStatus(ResStatus.STATUS_FAILED);
                result.setResMsg(ResStatus.STATUS_FAILED_MSG);
                return result;
            }

            map.setId(Long.valueOf(entityData.getId()));
            log.debug("新增数据返回 {}", rec);
            List<CompanyPurchaseSaveRequest> companyPurchaseSaveRequestList = map.getCompanyPurchaseSaveRequestList();
            List<TCompanyPurchase> tCompanyPurchaseList = new ArrayList<>();
            if (companyPurchaseSaveRequestList != null && companyPurchaseSaveRequestList.size() > 0) {
                for (CompanyPurchaseSaveRequest companyPurchaseSaveRequest : companyPurchaseSaveRequestList) {
                    TCompanyPurchase tCompanyPurchase = new TCompanyPurchase();
                    BeanUtils.copyProperties(companyPurchaseSaveRequest, tCompanyPurchase);
                    tCompanyPurchase.setCompanyId(Long.valueOf(entityData.getId()));
                    tCompanyPurchase.setCreateTime(new Date());
                    tCompanyPurchase.setUpdateTime(new Date());
                    tCompanyPurchase.setExpiryDate(DateFormatTool.stringToDate(DateFormatTool.DATE_FORMAT, companyPurchaseSaveRequest.getExpiryDate()));
                    tCompanyPurchase.setStartDate((DateFormatTool.stringToDate(DateFormatTool.DATE_FORMAT, companyPurchaseSaveRequest.getStartDate())));
                    if (tCompanyPurchase.getExpiryDate() != null && tCompanyPurchase.getStartDate() != null) {
                        if (tCompanyPurchase.getExpiryDate().getTime() >= new Date().getTime() && tCompanyPurchase.getStartDate().getTime() < new Date().getTime()) {
                            tCompanyPurchase.setIsEnabled(0);
                        }
                    }

                    tCompanyPurchaseList.add(tCompanyPurchase);
                }
                tCompanyPurchaseDao.insertBatch(tCompanyPurchaseList);
            }
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(map.getId());
                logSaveRequest.setRelatedType("custom");
                logSaveRequest.setLogTitle("新增客户信息");
                logSaveRequest.setLogContent("公司名称" + map.getCompanyName() + "," + getPurchaseOperateDetail(purchaseMap));
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("新增");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, ParamUtil.doChange());
            } catch (Exception e) {
                log.error(e.getMessage());
            }

            if (StringUtils.isNotEmpty(map.getMainMobile())) {
                //如果用户不存在  插入用户信息
                Map<String, String> userMap = new HashMap<>();
//                userMap.put("UserID",map.getMainMobile());
//                List<SYuser> sYuserList = sYuserDao.selectList(new Page<>(),userMap);
                SYuser sYuser = new SYuser();
                sYuser.setVldFG("0");
                sYuser.setCompanyID(entityData.getId() + "");
                sYuser.setName(map.getMainAccountName());
//                sYuser.setUserID(map.getMainMobile());
//                sYuser.setPhoneNo(map.getMainMobile());
                sYuser.setUserID(AESTool.encrypt(map.getMainMobile()));
                sYuser.setPhoneNo(AESTool.encrypt(map.getMainMobile()));
//                if(sYuserList.size() <= 0){
                RLock rLock = redissonCommand.getFairLock(map.getMainMobile());
                if (rLock.tryLock()) {
                    try {
                        boolean userExist = stringRedisTemplate.hasKey(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getMainMobile());
                        if (userExist) {
                            result.setResStatus(ResStatus.STATUS_USER_EXIT);
                            result.setResMsg(ResStatus.STATUS_USER_EXIT_MSG);
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return result;
                        }
                        int success = sYuserDao.insertRecords(sYuser);
                        if (success > 0) {
                            stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getMainMobile(), sYuser.getId() + "");
                        }
                    } catch (Exception e) {

                    } finally {
                        rLock.unlock();
                    }
                }


//                }
            }

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
//            result.setResData(page.setRecords(Arrays.asList(map)));
        } catch (Exception e) {
            log.error("新增数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增数据出错：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return result;
    }

    /**
     * 新增
     *
     * @param map
     * @param requestPojo
     * @return Result.class
     */
    @Override
    @Transactional
    public Result doUpdate(CompanySaveRequest map, RequestPojo requestPojo) {

        log.info("TCompanySvcImpl doUpdate {} ", map);
        Result result = new Result();
        //名称重复验证
        Page page = new Page();

        if (Objects.isNull(map.getId()) || map.getId() == 0) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG + "：未找到公司id");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

        List<CompanyResponse> entitys = null;
        Map<String, String> mapData = new HashMap<>();
        mapData.put("CompanyID", String.valueOf(map.getId()));
        mapData.put("CompanyName", map.getCompanyName());
        entitys = entitymDao.selectList(page, mapData);
        if (Objects.isNull(entitys) || entitys.size() == 0) {
            result.setResStatus(ResStatus.STATUS_UNAVAILABLE);
            result.setResMsg(ResStatus.STATUS_UNAVAILABLE_MSG);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        Map<String, Object> deleteMap = new HashMap<>();
        deleteMap.put("company_id", String.valueOf(map.getId()));
        int rec = entityContactDao.deleteByMap(deleteMap);
        log.debug("删除子记录数据返回 {}", rec);

        TCompany entityData = new TCompany();
        BeanUtils.copyProperties(map, entityData);
        entityData.setId(map.getId().intValue());
        entityData.setUpdateBy(requestPojo.getUserName());
        entityData.setUpdateTime(new Date());
        if (StringUtils.isNotEmpty(map.getIssueDate())) {
            entityData.setIssueDate(DateFormatTool.stringDateFormatToDate(map.getIssueDate()));
        }
        if (StringUtils.isNotEmpty(map.getProductionExpiryDate())) {
            entityData.setProductionExpiryDate(DateFormatTool.stringDateFormatToDate(map.getProductionExpiryDate()));
        }
        try {
            rec = entitymDao.update(entityData);
            map.setId(Long.valueOf(entityData.getId()));
            log.debug("更新数据返回 {}", rec);

            saveList(map, requestPojo);

            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);

            result.setResData(page.setRecords(Arrays.asList(map)));
            //如果用户不存在  插入用户信息


        } catch (Exception e) {
            log.error("修改数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("修改数据出错：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return result;
    }

    @Override
    public Result doDelete(CompanyQueryRequest map, RequestPojo requestPojo) {
        log.info("TCompanySvcImpl doDelete {} ", map);

        Result result = new Result();
        Page page = new Page();

        if (Objects.isNull(map.getId()) || map.getId() == 0) {
            result.setResStatus(ResStatus.STATUS_WRONGFUL);
            result.setResMsg(ResStatus.STATUS_WRONGFUL_MSG + "：未找到公司id");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

        int rec = entitymDao.deleteById(map.getId().intValue());
        log.debug("删除数据返回 {}", rec);

        Map<String, Object> mapData = new HashMap<>();
        mapData.put("company_id", String.valueOf(map.getId()));

        rec = entityContactDao.deleteByMap(mapData);
        log.debug("删除子记录数据返回 {}", rec);

        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);
        return result;
    }

    @Override
    @Transactional
    public Result backDataUpdate(CompanyBackSaveRequest map, RequestPojo requestPojo) {

        log.debug("TCompanySvcImpl.doSave parameter: {}", map);
        Result result = new Result();
        if(!requestPojo.getCustId().equals(COMPANY_ID)){
            result.setResStatus(ResStatus.STATUS_NOT_VJ_ERROR);
            result.setResMsg(ResStatus.STATUS_NOT_VJ_ERROR_MSG);
            return result;
        }
        TCompany entityCompany = new TCompany();
        entityCompany.setId(Integer.valueOf(map.getId() + ""));
        TCompany entityData = entitymDao.selectOne(entityCompany);
        if(Objects.isNull(entityData)){
            result.setResStatus(ResStatus.STATUS_ON_COMPANY_NOT_EXIST);
            result.setResMsg(ResStatus.STATUS_ON_COMPANY_NOT_EXIST_MSG);
            return result;
        }
        entityData.setCompanyName(map.getCompanyName());
        entityData.setMainMobile(map.getMainMobile());
        entityData.setRemark(map.getRemark());
        entityData.setUniformSocialCreditCode(map.getUniformSocialCreditCode());
        entityData.setMainAccountName(map.getMainAccountName());
       // BeanUtils.copyProperties(map, entityData);
//        entityData.setIsEnabled(0);
        entityData.setUpdateBy(requestPojo.getUserName());
        entityData.setUpdateTime(new Date());
        entityData.setId(Integer.valueOf(map.getId() + ""));
        Map<String, String> purchaseMap = new HashMap<>();
        if (map.getCompanyPurchaseSaveRequestList() != null && map.getCompanyPurchaseSaveRequestList().size() > 0) {
            for (CompanyPurchaseSaveRequest companyPurchaseSaveRequest : map.getCompanyPurchaseSaveRequestList()) {
                if (purchaseMap.containsKey(companyPurchaseSaveRequest.getPurchaseContractNo())) {
                    result.setResStatus(ResStatus.STATUS_CONTRACT_NO_EXIT);
                    result.setResMsg(ResStatus.STATUS_CONTRACT_NO_EXIT_MSG);
                    return result;
                }
                purchaseMap.put(companyPurchaseSaveRequest.getPurchaseContractNo(), companyPurchaseSaveRequest.getPurchaseContractNo());
            }
        }
        TCompanyPurchase purchase = new TCompanyPurchase();
        purchase.setCompanyId(map.getId());
        List<TCompanyPurchase> tCompanyPurchaseDataList = tCompanyPurchaseDao.queryAllByLimit(purchase);
        Map<String, String> dbPurchaseMap = new HashMap<>();
        for (TCompanyPurchase tCompanyPurchaseData : tCompanyPurchaseDataList) {
            dbPurchaseMap.put(tCompanyPurchaseData.getPurchaseContractNo(), tCompanyPurchaseData.getPurchaseContractNo());
        }
        Map<String, String> mapData = new HashMap<>();
        mapData.put("id", String.valueOf(map.getId()));
        List<TCompany> companyList = entitymDao.selectCustom(new Page<>(), mapData);
        try {
            int sus = 0;
            try {
                sus = entitymDao.update(entityData);
            } catch (Exception e) {
                if (ExceptionHandle.isDoubleKey(e)) {
                    result.setResStatus(ResStatus.STATUS_COMPANY_NO_DOUBLE);
                    result.setResMsg(ResStatus.STATUS_COMPANY_NO_DOUBLE_MSG);
                    return result;
                }
                log.error("公司更新失败" + e.getMessage());
            }
            if (sus <= 0) {
                result.setResStatus(ResStatus.STATUS_FAILED);
                result.setResMsg(ResStatus.STATUS_FAILED_MSG);
                return result;
            }

            Long rec = map.getId();
//            map.setId(Long.valueOf(entityData.getId()));
            log.debug("修改数据返回 {}", rec);
            tCompanyPurchaseDao.deleteByCompanyId(map.getId());
            List<CompanyPurchaseSaveRequest> companyPurchaseSaveRequestList = map.getCompanyPurchaseSaveRequestList();
            List<TCompanyPurchase> tCompanyPurchaseList = new ArrayList<>();
            if (companyPurchaseSaveRequestList != null && companyPurchaseSaveRequestList.size() > 0) {
                for (CompanyPurchaseSaveRequest companyPurchaseSaveRequest : companyPurchaseSaveRequestList) {
                    TCompanyPurchase tCompanyPurchase = new TCompanyPurchase();
                    BeanUtils.copyProperties(companyPurchaseSaveRequest, tCompanyPurchase);
                    tCompanyPurchase.setCompanyId(Long.valueOf(rec));
                    tCompanyPurchase.setCreateTime(new Date());
                    tCompanyPurchase.setUpdateTime(new Date());
                    tCompanyPurchase.setExpiryDate(DateFormatTool.stringToDate(DateFormatTool.DATE_FORMAT, companyPurchaseSaveRequest.getExpiryDate()));
                    tCompanyPurchase.setStartDate((DateFormatTool.stringToDate(DateFormatTool.DATE_FORMAT, companyPurchaseSaveRequest.getStartDate())));
                    if (tCompanyPurchase.getExpiryDate() != null && tCompanyPurchase.getStartDate() != null) {
                        if (tCompanyPurchase.getExpiryDate().getTime() >= new Date().getTime() && tCompanyPurchase.getStartDate().getTime() < new Date().getTime()) {
                            tCompanyPurchase.setIsEnabled(0);
                        }
                    }
                    tCompanyPurchaseList.add(tCompanyPurchase);
                }
                tCompanyPurchaseDao.insertBatch(tCompanyPurchaseList);
            }
            try {
                LogSaveRequest logSaveRequest = new LogSaveRequest();
                logSaveRequest.setRelatedId(map.getId());
                logSaveRequest.setRelatedType("custom");
                logSaveRequest.setLogTitle("修改客户信息");
                logSaveRequest.setLogContent("公司名称" + map.getCompanyName() + "," + getPurchaseOperateDetail(purchaseMap, dbPurchaseMap));
                logSaveRequest.setOperateTime(new Date());
                logSaveRequest.setOperateType("修改");
                logSaveRequest.setOperateStatus("成功");
                tSysLogSvc.doSave(logSaveRequest, ParamUtil.doChange());
            } catch (Exception e) {
                log.error(e.getMessage());
            }

            if (StringUtils.isNotEmpty(map.getMainMobile())) {
                //如果用户不存在  插入用户信息
                Map<String, String> userMap = new HashMap<>();
                userMap.put("UserID", map.getMainMobile());
//                List<SYuser> sYuserList = sYuserDao.selectList(new Page<>(),userMap);
//                if(sYuserList.size() <= 0){
                RLock rLock = redissonCommand.getFairLock(map.getMainMobile());
                SYuser sYuser = new SYuser();
                sYuser.setVldFG("0");
                sYuser.setCompanyID(requestPojo.getCustId());
                sYuser.setCompanyID(map.getId() + "");
                sYuser.setName(map.getMainAccountName());
//                    sYuser.setUserID(map.getMainMobile());
//                    sYuser.setPhoneNo(map.getMainMobile());
                sYuser.setUserID(AESTool.encrypt(map.getMainMobile()));
                sYuser.setPhoneNo(AESTool.encrypt(map.getMainMobile()));
                if (rLock.tryLock()) {
                    try {
                        boolean userExist = stringRedisTemplate.hasKey(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getMainMobile());

                        if (companyList.size() > 0 && StringUtils.isNotEmpty(companyList.get(0).getMainMobile())) {
                            String mainMobile = companyList.get(0).getMainMobile();
                            String redisId = stringRedisTemplate.opsForValue().get(RedisKeyConstant.USER_MODIFY_LOCK + ":" + mainMobile);
                            if (StringUtils.isNotEmpty(redisId)) {
                                if (!userExist) {
                                    sYuser.setId(Integer.valueOf(redisId));
                                    int success = sYuserDao.updateRecords(sYuser);
                                    if (success > 0) {
                                        stringRedisTemplate.opsForValue().set(RedisKeyConstant.USER_MODIFY_LOCK + ":" + map.getMainMobile(), sYuser.getId() + "");
                                        if (!mainMobile.equals(map.getMainMobile())) {
                                            stringRedisTemplate.delete(RedisKeyConstant.USER_MODIFY_LOCK + ":" + mainMobile);
                                        }
                                    }

                                } else {
                                    if (mainMobile.equals(map.getMainMobile())) {
                                        sYuser.setId(Integer.valueOf(redisId));
                                        int success = sYuserDao.updateRecords(sYuser);
                                    }
                                }
                            }
                        }


                    } catch (Exception e) {

                    } finally {
                        rLock.unlock();
                    }
                }
//                }
            }
            result.setResStatus(ResStatus.STATUS_SUCCESS);
            result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
//            result.setResData(page.setRecords(Arrays.asList(map)));
        } catch (Exception e) {
            log.error("新增数据出错", e);
            result.setResStatus(ResStatus.STATUS_DATABASE_FAIL);
            result.setResMsg("新增数据出错：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return result;
    }

    private String getPurchaseOperateDetail(Map<String, String> updateMap, Map<String, String> dbMap) {
        String result = "";
        StringBuilder stringBuilderInsert = new StringBuilder("新增合同号:");
        StringBuilder stringBuilderDelete = new StringBuilder("删除合同号:");
        for (String key : updateMap.keySet()) {
            if (!dbMap.containsKey(key)) {
                stringBuilderInsert.append(key + ",");
            }
        }
        for (String key : dbMap.keySet()) {
            if (!updateMap.containsKey(key)) {
                stringBuilderDelete.append(key + ",");
            }
        }
        return result + stringBuilderInsert + stringBuilderDelete;
    }

    private String getPurchaseOperateDetail(Map<String, String> updateMap) {
        String result = "";
        StringBuilder stringBuilderInsert = new StringBuilder("新增合同号:");
        for (String key : updateMap.keySet()) {
            stringBuilderInsert.append(key).append(",");
        }
        return result + stringBuilderInsert;
    }

    @Override
    public Result doBackQueryPage(CompanyBackQueryRequest data, RequestPojo requestPojo) {

        Result result = new Result();
        //分页查询产品信息表
        Page page = new Page();

        Map<String, String> map = MapTools.objectToMap(data);
        if(!requestPojo.getCustId().equals(COMPANY_ID)){
            result.setResStatus(ResStatus.STATUS_NOT_VJ_ERROR);
            result.setResMsg(ResStatus.STATUS_NOT_VJ_ERROR_MSG);
            return result;
        }
        map.put("companyId",requestPojo.getCustId());
        if (!StringUtils.isEmpty(map.get("pageSize")) && !StringUtils.isEmpty(map.get("currentPage"))) {
            page.setSize(Integer.parseInt(map.get("pageSize")));
            page.setCurrent(Integer.parseInt(map.get("currentPage")));
        }

        List<CompanyBackQueryResponse> companyBackQueryResponseList = new ArrayList<>();
        //分页处理 -- 20192021 Liby
        long total = com.github.pagehelper.PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                entitymDao.selectCustom(page, map);
            }
        });
        ParamUtil.setPage(page.getSize(), page.getCurrent(), page);
        List<TCompany> entitys = entitymDao.selectCustom(page, map);
        for (TCompany tCompany : entitys) {
            CompanyBackQueryResponse companyBackQueryResponse = new CompanyBackQueryResponse();
            BeanUtils.copyProperties(tCompany, companyBackQueryResponse);
            companyBackQueryResponse.setUpdateTime(DateFormatTool.dateToDefaultString(tCompany.getUpdateTime()));
            companyBackQueryResponse.setId(Long.valueOf(tCompany.getId()));
            companyBackQueryResponse.setRemark(tCompany.getRemark());
            companyBackQueryResponseList.add(companyBackQueryResponse);
        }

        if (data.getId() != null) {
            TCompanyPurchase tCompanyPurchase = new TCompanyPurchase();

            tCompanyPurchase.setCompanyId(data.getId());
            List<TCompanyPurchase> tCompanyPurchaseList = tCompanyPurchaseDao.queryAllByLimit(tCompanyPurchase);
            List<CompanyPurchaseResponse> companyPurchaseResponseList = new ArrayList<>();
            for (TCompanyPurchase tCompanyPurchaseData : tCompanyPurchaseList) {
                CompanyPurchaseResponse companyBackQueryResponse = new CompanyPurchaseResponse();
                BeanUtils.copyProperties(tCompanyPurchaseData, companyBackQueryResponse);
                companyBackQueryResponse.setUpdateTime(DateFormatTool.dateToDefaultString(tCompanyPurchaseData.getUpdateTime()));
                companyBackQueryResponse.setStartDate(DateFormatTool.dateToDateFormatString(tCompanyPurchaseData.getStartDate()));
                companyBackQueryResponse.setExpiryDate(DateFormatTool.dateToDateFormatString(tCompanyPurchaseData.getExpiryDate()));
                companyBackQueryResponse.setMaxUser(tCompanyPurchaseData.getMaxUser());
                companyPurchaseResponseList.add(companyBackQueryResponse);

            }
            companyBackQueryResponseList.get(0).setCompanyPurchaseResponseList(companyPurchaseResponseList);
        }

        page.setTotal((int) total);
        page.setRecords(companyBackQueryResponseList);
        result.setResStatus(ResStatus.STATUS_SUCCESS);
        result.setResMsg(ResStatus.STATUS_SUCCESS_MSG);
        result.setResData(page);

        return result;
    }

    /**
     * 保存公司联系信息
     *
     * @param map
     * @param requestPojo
     */
    private int saveList(CompanySaveRequest map, RequestPojo requestPojo) {

        TCompanyContact param = new TCompanyContact();
        param.setCompanyId(map.getId());
        param.setContactEmail(map.getContactEmail());
//        param.setContactFax(map.getContactFax());
        try {
            if(StringUtils.isNotEmpty(map.getContactMobile())){
                param.setContactMobile(AESTool.encrypt(map.getContactMobile()));
            }
            if(StringUtils.isNotEmpty(map.getContactTelephone())){
                param.setContactTelephone(AESTool.encrypt(map.getContactTelephone()));
            }
        }catch (Exception e){

        }

        param.setContactName(map.getContactName());
        int rec = entityContactDao.insert(param);
        log.debug("插入子记录数据返回 {}", rec);

        return rec;
    }

}
