package com.lightinit.hsdataplatform.impl.admin;

import com.lightinit.hsdataplatform.common.HttpUtil;
import com.lightinit.hsdataplatform.dictionary.DicCompanyAuthResult;
import com.lightinit.hsdataplatform.dictionary.DicNewGateway;
import com.lightinit.hsdataplatform.dictionary.DicUserAuthState;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.mapper.UserAuthSettingMapper;
import com.lightinit.hsdataplatform.mapper.UserCompanyMapper;
import com.lightinit.hsdataplatform.mapper.UserMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.CompanyUserDataModel;
import com.lightinit.hsdataplatform.model.admin.CompanyUserListModel;
import com.lightinit.hsdataplatform.model.admin.CompanyUserSearchModel;
import com.lightinit.hsdataplatform.service.admin.IUserCompanyService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class UserCompanyServiceImpl implements IUserCompanyService {

    private static Logger logger = LoggerFactory.getLogger(UserCompanyServiceImpl.class);
    @Autowired
    private UserCompanyMapper userCompanyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAuthSettingMapper userAuthSettingMapper;


    @Override
    public List<CompanyUserListModel> queryList(CompanyUserSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        if(DicCompanyAuthResult.PENDING.equals(inputModel.getDicCompanyState())){
            inputModel.setDicCompanyState("a");
        }
        return  userCompanyMapper.selectModelList(inputModel);
    }

    @Override
    public long queryCount(CompanyUserSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return userCompanyMapper.queryCount(inputModel);
    }

    @Override
    public CompanyUserDataModel queryOne(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        CompanyUserDataModel companyUserDataModel = new CompanyUserDataModel();
        UserCompanyWithBLOBs userCompanyWithBLOBs = userCompanyMapper.selectByPrimaryKey(id);
        User user = userMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(user,companyUserDataModel);
        BeanUtils.copyProperties(userCompanyWithBLOBs,companyUserDataModel);
        return  companyUserDataModel;
    }

    @Transactional
    @Override
    public ResultState edit(CompanyUserDataModel inputModel, int param) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        User user = new User();
        user.setId(inputModel.getId());
        user.setAuthState(DicUserAuthState.PENDING);
        user.setAuthOpinion(inputModel.getAuthOpinion());
        if(param==1) {
            user.setAuthResult(DicCompanyAuthResult.APPROVED);
            User requireUser = userMapper.selectByPrimaryKey(inputModel.getId());//需要注册时的用户名
            //审核通过，生成签名
            HashMap<String, String> authheaderMap = new HashMap<>();
            authheaderMap.put("content-type","application/json");
            HashMap<String, String> requestMap = new HashMap<>();
            requestMap.put("appId",DicNewGateway.APPLICATIONID);
            requestMap.put("userId",requireUser.getUsername());
            requestMap.put("signStatus","启用");
            try {
                String passMessage = HttpUtil.httpPost(DicNewGateway.SIGNADD, authheaderMap,requestMap);
                JSONObject userJson = JSONObject.fromObject(passMessage);
                if("success".equals(userJson.get("status"))&& "code".equals(userJson.get("code").toString())){
                    //2.------>同步到服务开发环境平台
                    //插入user_auth_setting表
                    UserAuthSetting userAuthSetting = new UserAuthSetting();
                    userAuthSetting.setUserId(user.getId());
                    userAuthSetting.setAuthSecret(userJson.get("result").toString());
                    UserAuthSettingExample example = new UserAuthSettingExample();
                    example.createCriteria().andUserIdEqualTo(user.getId());
                    userAuthSettingMapper.updateByExampleSelective(userAuthSetting,example);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("认证接口调用失败");
            }
        }
        else{
            user.setAuthResult(DicCompanyAuthResult.REJECTED);
        }
        int result1 = userMapper.updateByPrimaryKeySelective(user);

        UserCompanyWithBLOBs userCompanyWithBLOBs = new UserCompanyWithBLOBs();
        userCompanyWithBLOBs.setCreatedAt(new Date());
        userCompanyWithBLOBs.setId(inputModel.getId());
        int result2 =userCompanyMapper.updateByPrimaryKeySelective(userCompanyWithBLOBs);
        if (!( result1> 0 &&  result2> 0) ){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据更新失败");
        }
        resultState.setData(inputModel.getId());
        return resultState;
    }
}
