package com.github.wxiaoqi.security.admin.biz;

import com.github.wxiaoqi.security.admin.constant.enumerate.StaffChangeStatusEnum;
import com.github.wxiaoqi.security.admin.dto.AppUserPositionChangeRecordDTO;
import com.github.wxiaoqi.security.admin.dto.AppUserPositionTempDTO;
import com.github.wxiaoqi.security.admin.dto.AppUserPositionTempFindDTO;
import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.mapper.AppUserPositionTempMapper;
import com.github.wxiaoqi.security.admin.vo.AppUserPositionTempVo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.google.common.collect.Lists;
import com.xxfc.platform.vehicle.entity.BranchCompany;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

import static com.github.wxiaoqi.security.admin.biz.AppUserPositionChangeRecordBiz.*;


/**
 * 用户身份职位表
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-07-09 10:00:42
 */
@Transactional
@DependsOn("appUserPositionBiz")
@Service
@Slf4j
public class AppUserPositionTempBiz extends BaseBiz<AppUserPositionTempMapper, AppUserPositionTemp> implements InitializingBean {

    @Autowired
    private AppUserDetailBiz detailBiz;

    @Autowired
    private AppUserLoginBiz loginBiz;

    @Autowired
    private AppUserPositionBiz appUserPositionBiz;

    private Map<Integer, String> postionIdAndNameMap;

    @Autowired
    private VehicleFeign vehicleFeign;

    @Autowired
    AppUserJobLevelBiz jobLevelBiz;

    @Autowired
    AppUserPositionChangeRecordBiz appUserPositionChangeRecordBiz;

    @Autowired
    private AppShareholderDetailBiz appShareholderDetailBiz;


    public ObjectRestResponse add(AppUserPositionTempDTO appUserPositionTempDTO, Integer updUserId) {
        if (appUserPositionTempDTO == null || StringUtils.isBlank(appUserPositionTempDTO.getPhone()) || StringUtils.isBlank(appUserPositionTempDTO.getName())
                || appUserPositionTempDTO.getPositionId() == null || appUserPositionTempDTO.getPositionId() == 0) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "参数不能为空");
        }
        Integer companyId = appUserPositionTempDTO.getCompanyId();
        String companyName = appUserPositionTempDTO.getCompanyName();
        if (!(companyId != null && companyId > 0 && StringUtils.isNotBlank(companyName)))
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "分公司不存在");
        BranchCompany branchCompany = vehicleFeign.companyId(companyName);
        if (branchCompany == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "分公司不存在");
        }
        companyId = branchCompany.getId();
        companyName = branchCompany.getName();
        String phone = appUserPositionTempDTO.getPhone();
        Integer id = appUserPositionTempDTO.getId() == null ? 0 : appUserPositionTempDTO.getId();
        Example example = new Example(AppUserPositionTemp.class);
        example.createCriteria().andEqualTo("phone", phone).andNotEqualTo("id", id).andEqualTo("isDel", 0);
        List<AppUserPositionTemp> list = selectByExample(example);
        if (list.size() > 0) {
            return ObjectRestResponse.createFailedResult(ResultCode.EXIST_CODE, "手机号码已存在");
        }
        Integer userId = 0;
        AppUserLogin userLogin = loginBiz.checkeUserLogin(phone);
        if (userLogin != null) {
            userId = userLogin.getId();
        }
        AppUserPositionTemp userPositionTemp = new AppUserPositionTemp();
        BeanUtils.copyProperties(appUserPositionTempDTO, userPositionTemp);
        userPositionTemp.setUserId(userId);
        userPositionTemp.setCompanyId(companyId);
        userPositionTemp.setCompanyName(companyName);
        //编辑
        if (id == null || id == 0) {
            userPositionTemp.setIsQuit(0);
            int ids = addUserFindId(userPositionTemp).getId();
            appUserPositionTempDTO.setId(ids);
            //记录表插入
            //  appUserPositionTempDTO.setId();
            appUserPositionChangeRecordBiz.addJoinJobRecord(appUserPositionTempDTO, updUserId);
        } else {
            updateSelectiveById(userPositionTemp);
        }
        if (userId != 0) {
            //更改用户身份信息
            detailBiz.updateUserPositionByUserId(userId, appUserPositionTempDTO.getPositionId());
        }
        return ObjectRestResponse.succ();
    }

    //新增员工表时，获取自增长主键ID，插入变动记录表对应user_id字段
    public AppUserPositionTemp addUserFindId(AppUserPositionTemp userPositionTemp) {
        AppUserPositionTemp newAppUserPositionTemp = new AppUserPositionTemp();
        insertSelective(userPositionTemp);
        BeanUtils.copyProperties(userPositionTemp, newAppUserPositionTemp);
        return newAppUserPositionTemp;

    }

    public void updateAppuserPostionStatusById(Integer id, int status) {
        AppUserPositionTemp appUserPositionTemp = new AppUserPositionTemp();
        appUserPositionTemp.setId(id);
        appUserPositionTemp.setIsDel(status);
        mapper.updateByPrimaryKeySelective(appUserPositionTemp);
    }

    public PageDataVO<AppUserPositionTempVo> findWithPage(AppUserPositionTempFindDTO appUserPositionTempFindDTO) {
        PageDataVO<AppUserPositionTempVo> dataVO = new PageDataVO<>();
        Example example = new Example(AppUserPositionTemp.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel", 0);
        if (StringUtils.isNotEmpty(appUserPositionTempFindDTO.getName())) {
            criteria.andLike("name", String.format("%%%s%%", appUserPositionTempFindDTO.getName().trim()));
        }
        if (StringUtils.isNotEmpty(appUserPositionTempFindDTO.getPhone())) {
            criteria.andEqualTo("phone", appUserPositionTempFindDTO.getPhone());
        }
        if (Objects.nonNull(appUserPositionTempFindDTO.getPositionId())) {
            criteria.andEqualTo("positionId", appUserPositionTempFindDTO.getPositionId());
        }
        if (Objects.nonNull(appUserPositionTempFindDTO.getCompanyId())) {
            criteria.andEqualTo("companyId", appUserPositionTempFindDTO.getCompanyId());
        }
        if (Objects.nonNull(appUserPositionTempFindDTO.getStatus())) {
            if (DataStatus.USERED.code == appUserPositionTempFindDTO.getStatus()) {
                criteria.andNotEqualTo("userId", 0);
            }
            if (DataStatus.NO_USERED.code == appUserPositionTempFindDTO.getStatus()) {
                criteria.andEqualTo("userId", 0);
            }
        }
        example.setOrderByClause("upd_time desc");
        PageDataVO<AppUserPositionTemp> pageDataVO = PageDataVO.pageInfo(appUserPositionTempFindDTO.getPage(), appUserPositionTempFindDTO.getLimit(), () -> mapper.selectByExample(example));
        List<AppUserPositionTemp> data = pageDataVO.getData();
        if (CollectionUtils.isEmpty(data)) {
            dataVO.setData(Collections.EMPTY_LIST);
            dataVO.setPageNum(appUserPositionTempFindDTO.getPage());
            dataVO.setPageSize(appUserPositionTempFindDTO.getLimit());
            return dataVO;
        }

        List<Integer> postionIds = data.stream().map(AppUserPositionTemp::getPositionId).collect(Collectors.toList());
        Map<Integer, AppUserPosition> postionMap = appUserPositionBiz.findPostionIdAndPostionMapByIds(postionIds);
        List<Integer> jobIds = data.stream().map(AppUserPositionTemp::getJobId).collect(Collectors.toList());
        Map<Integer, AppUserJobLevel> jobMap = jobLevelBiz.findJobIdAndJobMapByIds(jobIds);
        List<AppUserPositionTempVo> appUserPositionTempVos = new ArrayList<>();
        AppUserPositionTempVo appUserPositionTempVo;
        for (AppUserPositionTemp appUserPositionTemp : data) {
            appUserPositionTempVo = new AppUserPositionTempVo();
            BeanUtils.copyProperties(appUserPositionTemp, appUserPositionTempVo);
            String postionName = postionMap == null ? "" : postionMap.get(appUserPositionTemp.getPositionId()) == null ? "" : postionMap.get(appUserPositionTemp.getPositionId()).getName();
            String jobName = jobMap == null ? "" : jobMap.get(appUserPositionTemp.getJobId()) == null ? "" : jobMap.get(appUserPositionTemp.getJobId()).getName();
            appUserPositionTempVo.setPositionName(postionName);
            appUserPositionTempVo.setJobName(jobName);
            appUserPositionTempVo.setStatus(appUserPositionTemp.getUserId() == null ? DataStatus.NO_USERED.code : appUserPositionTemp.getUserId() == 0 ? DataStatus.NO_USERED.code : DataStatus.USERED.code);
            appUserPositionTempVos.add(appUserPositionTempVo);
        }

        dataVO.setData(appUserPositionTempVos);
        dataVO.setPageSize(pageDataVO.getPageSize());
        dataVO.setPageNum(pageDataVO.getPageNum());
        dataVO.setTotalCount(pageDataVO.getTotalCount());
        dataVO.setTotalPage(pageDataVO.getTotalPage());
        return dataVO;
    }

    public Map<String, Object> importUserPostion(List<String[]> userPostionData, Integer operatorId) {
        Map<String, Object> result = new HashMap<>(2);
        List<Map<String, Object>> errorResult = Lists.newArrayList();
        Map<String, Object> errorResultMap;

        Set<Map.Entry<Integer, String>> entrySet = postionIdAndNameMap.entrySet();
        AppUserPositionTemp appUserPositionTemp;
        for (int i = 0; i < userPostionData.size(); i++) {
            String[] data = userPostionData.get(i);
            Integer postionId = null;
            String name = "";
            String phone = "";
            String postionName = "";
            try {
                name = data[0];
                phone = data[1];
                if (StringUtils.isEmpty(phone)) {
                    throw new BaseException("手机号为空");
                }
                postionName = data[2];
                if (StringUtils.isEmpty(postionName)) {
                    throw new BaseException("身份为空");
                }
                if (StringUtils.isNotBlank(name)) {
                    name.replaceAll(" ", "");
                }
                Example example = new Example(AppUserPositionTemp.class);
                example.createCriteria().andEqualTo("phone", phone).andEqualTo("isDel", 0);
                List<AppUserPositionTemp> list = selectByExample(example);
                Integer id = 0;
                Integer userId = 0;
                if (list.size() > 0) {
                    AppUserPositionTemp appUserPositionTemp1 = list.get(0);
                    id = appUserPositionTemp1.getId();
                    userId = appUserPositionTemp1.getUserId();
                }
                if (userId == null || userId == 0) {
                    //根据手机号查询userId
                    AppUserLogin userLogin = loginBiz.checkeUserLogin(phone);
                    if (Objects.nonNull(userLogin)) {
                        userId = userLogin.getId();
                    }
                }
                for (Map.Entry<Integer, String> integerStringEntry : entrySet) {
                    if (integerStringEntry.getValue().contains(postionName)) {
                        postionId = integerStringEntry.getKey();
                        break;
                    }
                }
                String companyName = data[3];
                Integer companyId = 0;
                if (StringUtils.isNotBlank(companyName)) {
                    BranchCompany branchCompany = vehicleFeign.companyId(companyName);
                    if (branchCompany != null) {
                        companyId = branchCompany.getId();
                        companyName = branchCompany.getName();
                    } else {
                        companyName = null;
                    }
                }
                String jobName = data[4];
                Integer jobId = 2;
                if (StringUtils.isNotBlank(jobName) && jobName.contains("销售")) {
                    jobId = 1;
                }
                appUserPositionTemp = new AppUserPositionTemp();
                appUserPositionTemp.setName(name);
                appUserPositionTemp.setPositionId(postionId);
                appUserPositionTemp.setPhone(phone);
                appUserPositionTemp.setCompanyId(companyId);
                appUserPositionTemp.setCompanyName(companyName);
                appUserPositionTemp.setJobId(jobId);
                if (userId != null && userId > 0) {
                    //更新用户身份信息
                    detailBiz.updateUserPositionByUserId(userId, postionId);
                    appUserPositionTemp.setUserId(userId);
                }
                if (id != null && id > 0) {
                    appUserPositionTemp.setId(id);
                    updateSelectiveById(appUserPositionTemp);
                } else {
                    //  insertSelective(appUserPositionTemp);
                    AppUserPositionTemp appUserPositionTempNew = new AppUserPositionTemp();
                    BeanUtils.copyProperties(appUserPositionTemp, appUserPositionTempNew);
                    appUserPositionTempNew = addUserFindId(appUserPositionTemp);
                    //记录表插入
                    appUserPositionChangeRecordBiz.addJoinJobRecord(appUserPositionTempNew, operatorId);
                }

            } catch (BaseException ex) {
                errorResultMap = new HashMap<>(1);
                errorResultMap.put("num", i);
                errorResultMap.put("msg", ex.getMessage());
                errorResult.add(errorResultMap);
            } catch (ArrayIndexOutOfBoundsException ex) {
                errorResultMap = new HashMap<>(1);
                errorResultMap.put("num", i);
                String msg = "";
                if (StringUtils.isEmpty(phone)) {
                    msg += "手机号码缺失";
                }
                if (StringUtils.isEmpty(postionName)) {
                    msg += ",身份信息缺失";
                }
                errorResultMap.put("msg", msg);
                errorResult.add(errorResultMap);
            } catch (Exception ex) {
                errorResultMap = new HashMap<>(1);
                errorResultMap.put("num", i);
                errorResultMap.put("msg", "数据" + Arrays.toString(data) + "保存失败");
                errorResult.add(errorResultMap);
            }
        }
        result.put("success", userPostionData.size() - errorResult.size());
        result.put("error", errorResult.size());
        result.put("data", errorResult);
        return result;
    }

    private enum DataStatus {
        USERED(1), NO_USERED(0);
        private int code;

        DataStatus(int code) {
            this.code = code;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        postionIdAndNameMap = appUserPositionBiz.findPostionIdAndNameMap() == null ? Collections.EMPTY_MAP : appUserPositionBiz.findPostionIdAndNameMap();
    }


    public void setPostionIdByPhone(String phone) {
        try {
            //根据手机号查询userId
            AppUserLogin userLogin = loginBiz.checkeUserLogin(phone);
            Integer userId = userLogin.getId();
            if (userLogin == null) {
                log.info("----用户不存在----phone===" + phone);
                return;
            }
            Integer postionId = appShareholderDetailBiz.findShareholderByUserIdOrPhone(null, phone);
            if (Objects.isNull(postionId)) {
                Example example = new Example(AppUserPositionTemp.class);
                example.createCriteria().andEqualTo("phone", phone).andEqualTo("isDel", 0);
                List<AppUserPositionTemp> list = selectByExample(example);
                if (CollectionUtils.isEmpty(list)) {
                    log.info("----用户无身份----phone===" + phone);
                    return;
                }
                AppUserPositionTemp positionTemp = list.get(0);
                if (positionTemp.getUserId() > 0) {
                    log.info("----用户已存在身份----phone===" + phone);
                    return;
                }
                positionTemp.setUserId(userId);
                int num = updateSelectiveByIdRe(positionTemp);
                if (num > 0) {
                    postionId = positionTemp.getPositionId();
                    log.info("----用户---postionId====" + postionId + "----phone===" + phone);
                    detailBiz.updateUserPositionByUserId(userId, postionId);
                }
            } else {
                detailBiz.updateUserPositionByUserId(userId, postionId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public AppUserPositionTemp getOne(Integer userId) {
        Example example = new Example(AppUserPositionTemp.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("isDel", 0);
        List<AppUserPositionTemp> list = selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }


    public List<Integer> getUserIdByParentCompany(List<Integer> parentCompanyId) {
        return mapper.getUserIdByParentCompany(parentCompanyId);
    }

    /**
     * 员工信息修改，插入变更记录表
     * zuoyh
     *
     * @param changeStatus
     * @param appUserPositionTempDTO
     * @return
     */
    public ObjectRestResponse addUserPositionChangeRecord(Integer changeStatus, AppUserPositionTempDTO appUserPositionTempDTO, Integer operatorId) {

        if (changeStatus == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "操作类型参数不能为空");
        }
        if (appUserPositionTempDTO == null || StringUtils.isBlank(appUserPositionTempDTO.getPhone()) || StringUtils.isBlank(appUserPositionTempDTO.getName())
                || appUserPositionTempDTO.getPositionId() == null || appUserPositionTempDTO.getPositionId() == 0 || appUserPositionTempDTO.getCompanyId() == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "参数不能为空");
        }
        AppUserPositionTemp userPositionTemp = new AppUserPositionTemp();
        Example example = new Example(AppUserPositionTemp.class);
        example.createCriteria().andEqualTo("id", appUserPositionTempDTO.getId());
        BeanUtils.copyProperties(appUserPositionTempDTO, userPositionTemp);
        AppUserPositionTemp oldData = selectById(appUserPositionTempDTO.getId());
        Long nowTime = System.currentTimeMillis();
        //2:人事变动(更换职位、身份)：需要删除记录后再新增一条记录
        //3：修改所属公司 直接修改即可
        //4：离职
        if (changeStatus.equals(POSITION_CHANGE) || changeStatus.equals(JOB_CHANGE)) {
            mapper.deleteByExample(example);
            userPositionTemp.setCrtTime(nowTime);
            userPositionTemp.setUpdTime(nowTime);
            insertSelective(userPositionTemp);
            //变更记录表插入
            appUserPositionChangeRecordBiz.addPositionChangeRecord(userPositionTemp, oldData, operatorId, appUserPositionTempDTO.getRelTime());
        } else if (changeStatus.equals(COMPANY_CHANGE)) {
            userPositionTemp.setUpdTime(nowTime);
            updateSelectiveById(userPositionTemp);
            //变更记录表插入
            appUserPositionChangeRecordBiz.addPositionChangeRecord(userPositionTemp, oldData, operatorId, appUserPositionTempDTO.getRelTime());
        } else {
            userPositionTemp.setUpdTime(nowTime);
            updateSelectiveById(userPositionTemp);
            appUserPositionTempDTO.setPositionId(6);
            appUserPositionChangeRecordBiz.addPositionChangeRecord(userPositionTemp, oldData, operatorId, appUserPositionTempDTO.getRelTime());
        }
        if (Objects.nonNull(appUserPositionTempDTO.getUserId()) && !Objects.equals(0,appUserPositionTempDTO.getUserId())) {
            if (StaffChangeStatusEnum.needChangePostionsStatus.contains(changeStatus)) {
                //用户表更改其身份
                AppUserDetail appUserDetail = detailBiz.checkeIsAppUser(userPositionTemp.getUserId());
                if(Objects.nonNull(appUserDetail) && Objects.nonNull(appUserDetail.getUserid())) {
                    //1.查询股东表 根据userid 或 手机号
                    Integer postionId = appShareholderDetailBiz.findShareholderByUserIdOrPhone(appUserPositionTempDTO.getUserId(), appUserPositionTempDTO.getPhone());
                    //离职
                    if (StaffChangeStatusEnum.JOB_SEPARATION.getCode() == changeStatus) {
                        if (Objects.isNull(postionId)) {
                            //更改为普通用户 6
                            loginBiz.updateUserPosition(appUserDetail.getUserid(), 6);
                        }
                    }
                    //身份变更
                    if (StaffChangeStatusEnum.IDENTITY_CHANE.getCode() == changeStatus) {
                        //不是离职状态下
                        if (Objects.nonNull(userPositionTemp.getIsQuit()) && userPositionTemp.getIsQuit() != 1) {
                            postionId = Objects.nonNull(postionId) ? postionId : appUserPositionTempDTO.getPositionId();
                            //更改为股东身份
                            loginBiz.updateUserPosition(appUserDetail.getUserid(), postionId);
                        }
                    }
                }
            }
        }

        return ObjectRestResponse.succ();
    }

    /**
     * 员工复职
     */
    public ObjectRestResponse andAddUserPositionChangeRecord(AppUserPositionTempDTO appUserPositionTempDTO, Integer operatorId) {
        if (appUserPositionTempDTO == null || StringUtils.isBlank(appUserPositionTempDTO.getPhone())) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "参数不能为空");
        }
        AppUserPositionTemp userPositionTemp = new AppUserPositionTemp();
        BeanUtils.copyProperties(appUserPositionTempDTO, userPositionTemp);
        updateSelectiveById(userPositionTemp);
        userPositionTemp.setUpdTime(System.currentTimeMillis());
        appUserPositionChangeRecordBiz.andAddJoinJobRecord(appUserPositionTempDTO, operatorId);
        //用户表更改其身份
        if (Objects.nonNull(appUserPositionTempDTO.getUserId())) {
            AppUserDetail appUserDetail = detailBiz.checkeIsAppUser(userPositionTemp.getUserId());
            if (appUserDetail != null && Objects.nonNull(appUserDetail.getUserid())) {
                Integer postionId = appShareholderDetailBiz.findShareholderByUserIdOrPhone(appUserPositionTempDTO.getUserId(), appUserPositionTempDTO.getPhone());
                postionId = Objects.isNull(postionId) ? appUserPositionTempDTO.getPositionId() : postionId;
                loginBiz.updateUserPosition(appUserDetail.getUserid(), postionId);
            }
        }
        return ObjectRestResponse.succ();
    }

    /**
     * 查询员工信息变更记录表
     */

    public List<AppUserPositionChangeRecordDTO> findPositionChangeRecord(AppUserPositionTemp userPositionTemp) {
        return appUserPositionChangeRecordBiz.findPositionChangeRecord(userPositionTemp);
    }

    /**
     * zuoyh
     * app用户表修改职位，员工记录表对应查询
     */
    public void findUserPositionTemp(Integer userId, Integer positionId, Integer operatorId) {
        Timestamp relTime = new Timestamp(System.currentTimeMillis());
        Example example = new Example(AppUserPositionTemp.class);
        example.createCriteria().andEqualTo("userId", userId);
        List<AppUserPositionTemp> list = mapper.selectByExample(example);
        AppUserPositionTemp newAppUserPositionTemp = new AppUserPositionTemp();
        if (list.size() != 0) {
            newAppUserPositionTemp = list.get(0);
            if (newAppUserPositionTemp != null) {
                AppUserPositionTemp odlAppUserPositionTemp = new AppUserPositionTemp();
                BeanUtils.copyProperties(newAppUserPositionTemp, odlAppUserPositionTemp);
                newAppUserPositionTemp.setPositionId(positionId);
                newAppUserPositionTemp.setUpdTime(System.currentTimeMillis());
                mapper.updateByPrimaryKey(newAppUserPositionTemp);
                appUserPositionChangeRecordBiz.addPositionChangeRecord(newAppUserPositionTemp, odlAppUserPositionTemp, operatorId, relTime);
            }
        }
    }

}

