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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormColumn;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormColumnServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormInstanceServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.cache.Redis;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;


import java.util.*;

import static org.typroject.tyboot.component.cache.Redis.redisTemplate;

@Service
public class OrgServiceImpl {

    @Autowired
    OrgUsrServiceImpl orgUsrServiceImpl;

    @Autowired
    DynamicFormColumnServiceImpl dynamicFormColumnServiceImpl;

    @Autowired
    DynamicFormInstanceServiceImpl alertFormValueServiceImpl;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 保存或更新orgUsr信息和FormInstance实体信息
     * sequenceNbr表示 若是更新动态表单，则传orgUsr表的sequenceNbr，
     *                  若是新增信息，传null
     * @param jsonObject 表单数据
     * @param bizOrgType 数据类型（企业、人员、部门）
     * @param sequenceNbr 有值更新 ，没值保存
     * @return
     */
    public OrgUsrDto dataHandling(JSONObject jsonObject, String bizOrgType,String sequenceNbr){
        OrgUsr orgUsr = saveOrgUsr(jsonObject,bizOrgType,sequenceNbr);
        //条件构造器 找出column表种 类型为（COMPANY 或 DEPARTMENT 或 PERSON）的列
        LambdaQueryWrapper<DynamicFormColumn> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DynamicFormColumn::getGroupCode,bizOrgType);
        List<DynamicFormColumn> dynamicFormColumnList= dynamicFormColumnServiceImpl.list(wrapper);
        List<DynamicFormInstance> dynamicFormInstanceList = new ArrayList<>();
        Map<String, Long> map = new HashMap<>();
        for (DynamicFormColumn dynamicFormColumn : dynamicFormColumnList) {
            //将column表的基本字段信息给instance表
            DynamicFormInstance dynamicFormInstance = new DynamicFormInstance();
            BeanUtils.copyProperties(dynamicFormColumn, dynamicFormInstance);
            dynamicFormInstance.setFormColumnId(dynamicFormColumn.getSequenceNbr());
            //通过字段名去拿到表单传来的值
            dynamicFormInstance.setFieldValue(jsonObject.getString(dynamicFormInstance.getFieldCode()));
            dynamicFormInstance.setInstanceId(orgUsr.getSequenceNbr());
            dynamicFormInstance.setSequenceNbr(null);
            dynamicFormInstanceList.add(dynamicFormInstance);
        }
        //如果sequenceNbr有值（更新）
        if(!ValidationUtil.isEmpty(sequenceNbr)){
            LambdaQueryWrapper<DynamicFormInstance> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DynamicFormInstance ::getInstanceId,orgUsr.getSequenceNbr());
            List<DynamicFormInstance> instanceList = alertFormValueServiceImpl.list(lambdaQueryWrapper);
            //如果instance表中有值
            if(!ValidationUtil.isEmpty(instanceList)){
                //将查到的instance信息装到map中
                for(DynamicFormInstance dynamicFormInstance:instanceList){
                    map.put(dynamicFormInstance.getFieldCode(),dynamicFormInstance.getSequenceNbr());
                }
                //将查到的instance信息中的sequenceNbr装到更新之后的表中。
                for(DynamicFormInstance dynamicFormInstance:dynamicFormInstanceList){
                    dynamicFormInstance.setSequenceNbr(map.get(dynamicFormInstance.getFieldCode()));
                }
            }
        }
        //保存或更新 根据sequenceNbr
        alertFormValueServiceImpl.saveOrUpdateBatch(dynamicFormInstanceList);
        OrgUsrDto orgUsrDto = new OrgUsrDto();
        BeanUtils.copyProperties(orgUsr,orgUsrDto);
        orgUsrDto.setDynamicFormValue(dynamicFormInstanceList);
        return orgUsrDto;
    }

    /**
     * 更新或保存orgUsr表信息
     * @param jsonObject
     * @param bizOrgType
     * @return
     */
    public OrgUsr saveOrgUsr(JSONObject jsonObject,String bizOrgType,String sequenceNbr){
        ReginParams reginParams = getReginParams();
        OrgUsr orgUsr = new OrgUsr();
        if(!ValidationUtil.isEmpty(sequenceNbr)) {
            if (!ValidationUtil.isEmpty(orgUsrServiceImpl.getById(sequenceNbr))) {
                orgUsr = orgUsrServiceImpl.getById(sequenceNbr);
            }
        }
        orgUsr.setRecDate(new Date());
        AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
        orgUsr.setRecUserName(user.getRealName());
        orgUsr.setRecUserId(user.getUserId());
        orgUsr.setBizOrgName(jsonObject.getString("name"));
        orgUsr.setSequenceNbr(jsonObject.getLong("sequenceNbr"));
        orgUsr.setBizOrgType(bizOrgType);

        if (OrgPersonEnum.公司.getKey().equals(bizOrgType)){
            orgUsr.setOrgExpandAttr1(jsonObject.getString("type"));
            orgUsr.setBizOrgCode(jsonObject.getString("creditCode"));
            orgUsr.setAmosOrgId(jsonObject.getString("amosOrgId"));
            orgUsr.setAmosOrgCode(jsonObject.getString("amosOrgCode"));
        }
        if (OrgPersonEnum.人员.getKey().equals(bizOrgType)){
            if (1==jsonObject.getInteger("isWelder")) {
                orgUsr.setOrgExpandAttr1(OrgPersonEnum.焊工.getKey());
            }
            LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(reginParams.getCompany().getSequenceNbr()));
            orgUsr.setParentId(String.valueOf(orgUsrServiceImpl.getOne(wrapper).getSequenceNbr()));
        }
        if (OrgPersonEnum.部门.getKey().equals(bizOrgType)) {

        }
        //设置bizOrgCode
        if (orgUsr.getParentId() != null) {
            OrgUsr parent = orgUsrServiceImpl.getById(orgUsr.getParentId());
            if (parent != null && ObjectUtils.isEmpty(orgUsr.getBizOrgCode())) {
                orgUsr.setBizOrgCode(parent.getBizOrgCode() + OrgUsrServiceImpl.getOrgCodeStr());
            }
        } else {
            orgUsr.setBizOrgCode(OrgUsrServiceImpl.getOrgCodeStr());
        }

        orgUsrServiceImpl.saveOrUpdate(orgUsr);
        return orgUsr;
    }

    /**
     * 用户单位信息redis获取
     **/
    public ReginParams getReginParams() {
        return JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
    }

    /**
     * 获取企业下的焊工信息列表
     * @param companyId 单位/企业id
     * @return
     */
    public List<Map> getInfo(String companyId){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getSequenceNbr ,companyId);
        OrgUsr orgUsrCompany = orgUsrServiceImpl.getOne(wrapper);

        LambdaQueryWrapper<OrgUsr> welderWrapper = new LambdaQueryWrapper<>();
        welderWrapper.likeRight(OrgUsr :: getBizOrgCode,orgUsrCompany.getBizOrgCode()).eq(OrgUsr :: getOrgExpandAttr1, OrgPersonEnum.焊工.getKey());
        List<OrgUsr> orgUsrList = orgUsrServiceImpl.list(welderWrapper);

        List<Map> mapList = new ArrayList<>();
        for (OrgUsr orgUsr : orgUsrList) {
            Map map = getdetialInfo(String.valueOf(orgUsr.getSequenceNbr()));
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 根据id查询详细信息
     * @param sequenceNbr
     * @return
     */
    public Map getdetialInfo(String sequenceNbr){
        Map map = new HashMap();
        LambdaQueryWrapper<DynamicFormInstance> instanceWrapper = new LambdaQueryWrapper<>();
        instanceWrapper.eq(DynamicFormInstance :: getInstanceId,sequenceNbr);
        List<DynamicFormInstance> dynamicFormInstanceList = alertFormValueServiceImpl.list(instanceWrapper);
        for (DynamicFormInstance dynamicFormInstance : dynamicFormInstanceList) {
            map.put(dynamicFormInstance.getFieldCode(),dynamicFormInstance.getFieldValue());
        }
        return map;
    }

    /**
     * 获取当前登陆人所在公司/单位/企业 下的 所有焊工人员
     * @return
     */
    public List<Map> getCompanyWelder(){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(getReginParams().getCompany().getSequenceNbr()));
        return getInfo(String.valueOf(orgUsrServiceImpl.getOne(wrapper).getSequenceNbr()));
    }

    /**
     * 获取下拉选择值
     * @param type INSTALL("安装单位")、DESIGN("设计单位")
     * @return
     */
    public List<OrgUsr> getSelectInfo(String type){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getOrgExpandAttr1,type);
       return  orgUsrServiceImpl.list(wrapper);
    }

    /**
     * 查询当前登录单位下的人员列表
     * @return
     */
    public List<OrgUsr> getCharge(){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(getReginParams().getCompany().getSequenceNbr()));
        LambdaQueryWrapper<OrgUsr> personWrapper = new LambdaQueryWrapper<>();
        personWrapper.eq(OrgUsr::getParentId,orgUsrServiceImpl.getOne(wrapper).getSequenceNbr())
                .eq(OrgUsr :: getBizOrgType,OrgPersonEnum.人员.getKey());
        return orgUsrServiceImpl.list(personWrapper);
    }
}
