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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.dto.OrgusrDataxDto;
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.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.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProjectResourceEnum;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProjectResource;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
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 org.typroject.tyboot.core.restful.utils.ResponseHelper;


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());
            //通过字段名去拿到表单传来的值
            if("image".equals(dynamicFormColumn.getFieldCode())){
                dynamicFormInstance.setFieldValue(JSON.toJSONString(jsonObject.getJSONArray(dynamicFormInstance.getFieldCode())));
            }else{
                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());
        orgUsr.setBizOrgName(jsonObject.getString("name"));
        orgUsr.setSequenceNbr(jsonObject.getLong("sequenceNbr"));
        orgUsr.setBizOrgType(bizOrgType);
        orgUsr.setAmosOrgId(jsonObject.getString("amosOrgId"));
        orgUsr.setAmosOrgCode(jsonObject.getString("amosOrgCode"));

        if (OrgEnum.公司.getKey().equals(bizOrgType)){
            orgUsr.setOrgExpandAttr1(jsonObject.getString("type"));
            orgUsr.setBizOrgCode(jsonObject.getString("creditCode"));
        }
        if (OrgEnum.普通人员.getKey().equals(bizOrgType)){
            if(!ValidationUtil.isEmpty(jsonObject.getInteger("isWelder"))){
                if(ValidationUtil.isEmpty(sequenceNbr)){
                    if (1==jsonObject.getInteger("isWelder")) {
                        orgUsr.setOrgExpandAttr1(OrgEnum.焊工.getKey());
                        orgUsr.setCode(getCode());
                    }
                }
            }
            LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
            if (!ValidationUtil.isEmpty(jsonObject.getLong("isCheck"))) {
                wrapper.eq(OrgUsr :: getAmosOrgId,jsonObject.getLong("isCheck"));
            } else {
                wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(reginParams.getCompany().getSequenceNbr()));
            }

            orgUsr.setParentId(String.valueOf(orgUsrServiceImpl.getOne(wrapper).getSequenceNbr()));
        }
        if (OrgEnum.部门.getKey().equals(bizOrgType)) {
            LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(reginParams.getCompany().getSequenceNbr()));
            orgUsr.setParentId(String.valueOf(orgUsrServiceImpl.getOne(wrapper).getSequenceNbr()));
        }
        //设置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;
    }

    public String getCode(){
        int c;
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(OrgUsr::getCode).eq(OrgUsr::getOrgExpandAttr1,OrgEnum.焊工.getKey());
        String code = orgUsrServiceImpl.list(wrapper).iterator().next().getCode();
        if(ValidationUtil.isEmpty(code)){
            c = 0001;
        }else{
            c = Integer.parseInt(code.substring(code.indexOf("-")+1,code.length()))+1;
        }

        String welderCode = OrgEnum.焊工.getKey() +"-"+ c;
        return welderCode;
    }

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

    /**
     * 获取企业下的焊工信息列表
     * @param companyId 单位/企业id
     * @return
     */
    public IPage getInfo(String companyId,IPage page){
        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, OrgEnum.焊工.getKey());
        List<OrgUsr> orgUsrList = new ArrayList<>();
        if(ValidationUtil.isEmpty(page)){
            orgUsrList = orgUsrServiceImpl.list(welderWrapper);
            page = new Page();
        }else{
            orgUsrList = orgUsrServiceImpl.page(page,welderWrapper).getRecords();
        }

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

    /**
     * 根据id查询详细信息
     * @param sequenceNbr
     * @return
     */
    public Map getdetialInfo(String sequenceNbr){
        Map map = new HashMap();
        OrgUsr orgUsr = getOrgUsrById(sequenceNbr);
        String type = orgUsr.getOrgExpandAttr1();
        LambdaQueryWrapper<DynamicFormInstance> instanceWrapper = new LambdaQueryWrapper<>();
        instanceWrapper.eq(DynamicFormInstance :: getInstanceId,sequenceNbr);
        List<DynamicFormInstance> dynamicFormInstanceList = alertFormValueServiceImpl.list(instanceWrapper);
        map.put("type",type);
        map.put("sequenceNbr",sequenceNbr);
        for (DynamicFormInstance dynamicFormInstance : dynamicFormInstanceList) {
            if("image".equals(dynamicFormInstance.getFieldCode())){
                if(!ValidationUtil.isEmpty(dynamicFormInstance.getFieldValue())){
                    map.put(dynamicFormInstance.getFieldCode(),JSON.parseArray(dynamicFormInstance.getFieldValue()));
                }
            } else {
                map.put(dynamicFormInstance.getFieldCode(), dynamicFormInstance.getFieldValue());
            }
        }
        return map;
    }
    /**
     * 获取当前登陆人的建设单位和建设单位的组织机构代码
     * @return
     */
    @BusinessIdentify
    public Map getConstructionInfo(){
        ReginParams reginParams = getReginParams();
        ReginParams.BusinessInfo businessInfo = reginParams.getBusinessInfo();
        Long companySequenceNbr = businessInfo.getCompanySequenceNbr();
        return getdetialInfo(String.valueOf(companySequenceNbr));
    }


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

    /**
     * 获取当前登陆人所在公司/单位/企业 下的 所有部门
     * @return
     */
    public IPage getCompanyDept(IPage page){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(getReginParams().getCompany().getSequenceNbr()));
        LambdaQueryWrapper<OrgUsr> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(OrgUsr :: getParentId,orgUsrServiceImpl.getOne(wrapper).getSequenceNbr())
                        .eq(OrgUsr ::getBizOrgType, OrgEnum.部门.getKey());
        IPage<OrgUsr> list = orgUsrServiceImpl.page(page,wrapper1);
        List<Map> mapList = new ArrayList<>();
        for(OrgUsr orgUsr: list.getRecords()){
            mapList.add(getdetialInfo(String.valueOf(orgUsr.getSequenceNbr())));
        }
        page.setRecords(mapList);
        return page;
    }

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

    /**
     * 查询当前登录单位下的人员列表
     * @return
     */
    @BusinessIdentify
    public List<OrgUsr> getCharge(){
        LambdaQueryWrapper<OrgUsr> personWrapper = new LambdaQueryWrapper<>();
        personWrapper.eq(OrgUsr::getParentId,String.valueOf(getReginParams().getBusinessInfo().getCompanySequenceNbr()))
                .eq(OrgUsr :: getBizOrgType,OrgEnum.普通人员.getKey());
        return orgUsrServiceImpl.list(personWrapper);
    }

    /**
     * 获取当前登陆人所在单位id（orgUsr表中的id）
     * @return
     */
    public Long getCompanyId(){
        return getOrgUsr().getSequenceNbr();
    }

    /**
     * 获取当前登陆人所在单位信息（orgUsr表的）
     * @return
     */
    public OrgUsr getOrgUsr(){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getAmosOrgId,String.valueOf(getReginParams().getCompany().getSequenceNbr()));
        OrgUsr orgUsr = orgUsrServiceImpl.getOne(wrapper);
        if(ValidationUtil.isEmpty(orgUsr)){
            return  null;
        }
        return orgUsr;
    }

    /**
     * 根据id获取OrgUsr表的详细信息
     */
    public OrgUsr getOrgUsrById(String sequenceNbr){
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrgUsr :: getSequenceNbr,sequenceNbr);
        OrgUsr orgUsr = orgUsrServiceImpl.getOne(wrapper);
        if(ValidationUtil.isEmpty(orgUsr)){
            return  null;
        }
        return orgUsr;
    }

    /**
     * 根据parentId获取OrgUsr表的详细信息列表
     */
    public List<OrgUsr> getOrgUsrByParentId(String sequenceNbr){
        OrgUsr orgUsr = getOrgUsrById(sequenceNbr);
        LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(OrgUsr :: getBizOrgCode,orgUsr.getBizOrgCode())
                .eq(OrgUsr::getBizOrgType,OrgEnum.普通人员.getKey())
                .ne(OrgUsr::getOrgExpandAttr1,OrgEnum.焊工.getKey());
        List<OrgUsr> orgUsrList = orgUsrServiceImpl.list(wrapper);
        return orgUsrList;
    }

    /**
     * 根据OrgUsr表的sequenceNbr删除instance表的数据
     * @param sequencenNbr
     * @throws Exception
     */
    public void delectInfo(String sequencenNbr) throws Exception {
        OrgUsr orgUsr = getOrgUsrById(sequencenNbr);
        LambdaQueryWrapper<DynamicFormInstance> dynamicWrapper = new LambdaQueryWrapper<>();
        if(OrgEnum.普通人员.getKey().equals(orgUsr.getBizOrgType())){
            dynamicWrapper.eq(DynamicFormInstance::getInstanceId,sequencenNbr);
            alertFormValueServiceImpl.remove(dynamicWrapper);
        }else{
            LambdaQueryWrapper<OrgUsr> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrgUsr::getParentId,sequencenNbr);
            List<OrgUsr> orgUsrList = orgUsrServiceImpl.list(wrapper);
            if(ValidationUtil.isEmpty(orgUsrList)){
                dynamicWrapper.eq(DynamicFormInstance::getInstanceId,sequencenNbr);
                alertFormValueServiceImpl.remove(dynamicWrapper);
            }else {
                throw new Exception("该企业/部门下还有人员，不可删除！");
            }
        }
        orgUsrServiceImpl.deleteBySeq(Long.valueOf(sequencenNbr));
    }




    /**
     * 获取企业下的人员信息列表
     * @param companyId 单位/企业id
     * @return
     */
    public IPage getPersonInfo(String companyId,IPage page){
        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 :: getBizOrgType, OrgEnum.普通人员.getKey());
        List<OrgUsr> orgUsrList = new ArrayList<>();
        if(ValidationUtil.isEmpty(page)){
            orgUsrList = orgUsrServiceImpl.list(welderWrapper);
            page = new Page();
        }else{
            orgUsrList = orgUsrServiceImpl.page(page,welderWrapper).getRecords();
        }

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