package com.gree.mall.manager.logic.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.admin.AdminWebsitTree;
import com.gree.mall.manager.bean.admin.AdminWebsitVO;
import com.gree.mall.manager.bean.admin.reqDto.AdminUserAddReqBean;
import com.gree.mall.manager.bean.admin.reqDto.AdminUserPermissions;
import com.gree.mall.manager.commonmapper.AdminMapper;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.LbsAmapLogic;
import com.gree.mall.manager.plus.entity.AdminCompanyWechat;
import com.gree.mall.manager.plus.entity.AdminWebsit;
import com.gree.mall.manager.plus.entity.AdminZone;
import com.gree.mall.manager.plus.entity.SysDictCompany;
import com.gree.mall.manager.plus.service.AdminCompanyWechatService;
import com.gree.mall.manager.plus.service.AdminWebsitService;
import com.gree.mall.manager.plus.service.AdminZoneService;
import com.gree.mall.manager.plus.service.SysDictCompanyService;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminWebsitLogic {

    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    AdminZoneService adminZoneService;
    @Autowired
    CommonLogic commonLogic;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;

    @Autowired
    SysDictCompanyService sysDictCompanyService;

    @Autowired
    AdminUserLogic adminUserLogic;

    @Autowired
    LbsAmapLogic lbsAmapLogic;

    /**
     * 区域列表
     */
    public List<AdminZone> adminZoneList(){
        List<AdminZone> list = adminZoneService.list();
        return list;
    }

    /**
     * 部门树
     */
    public List<AdminWebsitTree> tree(HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        List<AdminWebsit> list = adminWebsitService.lambdaQuery()
//                .in(CollectionUtils.isNotEmpty(adminUser.getCorpIds()),AdminWebsit::getCorpId,adminUser.getCorpIds())
                .list();
        List<AdminWebsitTree> trees = new ArrayList<>();
        for(AdminWebsit adminWebsit : list){
            AdminWebsitTree adminWebsitTree = new AdminWebsitTree();
            BeanUtils.copyProperties(adminWebsit,adminWebsitTree);
            trees.add(adminWebsitTree);
        }

        List<AdminWebsitTree> parentList = trees.stream().filter(x -> x.getParentId() == 0).collect(Collectors.toList());
        for(AdminWebsitTree adminWebsit:parentList){
            adminWebsit.setChildren(this.treeModule(trees,adminWebsit.getWebsitId(),adminWebsit.getCompanyId()));
        }
        return parentList;
    }


    /**
     *  新增部门
     */
    @Transactional
    public void add(AdminWebsit adminWebsit, HttpServletRequest request) throws WxErrorException, RemoteServiceException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        Integer count = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getWebsitNumber,adminWebsit.getWebsitNumber())
                .or()
                .eq(AdminWebsit::getName, adminWebsit.getName())
                .count();
        if(count > 0){
            throw new RemoteServiceException("部门名称或部门编号已存在");
        }

        if (StringUtil.isEmpty(adminWebsit.getCompanyId()))
            throw new RemoteServiceException("上级商家不能为空");
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(adminWebsit.getPayWorkerCodeId());
        AdminCompanyWechat adminCompanyWechatP = adminCompanyWechatService.getById(adminWebsit.getCompanyId());


        adminWebsit.setWebsitId(adminWebsit.getWebsitNumber());
        adminWebsit.setCompanyName(adminCompanyWechatP.getCompanyName());
        adminWebsit.setPayWorkerCodeName(adminCompanyWechat.getCompanyName());
        adminWebsit.insert();

        AdminUserAddReqBean adminUserBean = new AdminUserAddReqBean();
        adminUserBean.setUserName(adminWebsit.getWebsitId());
        adminUserBean.setNickName(adminWebsit.getName());
        adminUserBean.setLinkPhone(adminWebsit.getPersonMobile());
        adminUserBean.setLinkName(adminWebsit.getPerson());
        adminUserBean.setPassword("123456");
        adminUserBean.setRoleId("1899638664615489538");
        adminUserBean.setRoleName("网点");
        adminUserBean.setWebsitId(adminWebsit.getWebsitId());
        adminUserBean.setWebsitName(adminWebsit.getName());
        adminUserBean.setCompanyId(adminWebsit.getCompanyId());
        adminUserBean.setCompanyName(adminWebsit.getCompanyName());
        adminUserBean.setAddress(adminWebsit.getAddress());
        adminUserBean.setType(2);

        List<AdminUserPermissions> adminUserPermissions = new ArrayList<>();
        AdminUserPermissions adminUserPermissions1 = new AdminUserPermissions();
        adminUserPermissions1.setAdminUserPermissionsId(adminWebsit.getWebsitId());
        adminUserPermissions1.setIsDept(false);
        adminUserPermissions.add(adminUserPermissions1);

        adminUserBean.setPermissions(adminUserPermissions);
        adminUserLogic.save(adminUserBean, request);

    }
    /**
     * 编辑部门
     */
    @Transactional
    public void update(AdminWebsit adminWebsit,HttpServletRequest request) throws RemoteServiceException, WxErrorException {

        //AdminUserCom adminUser = commonLogic.getAdminUser(request);

        Integer count = adminWebsitService.lambdaQuery()
                .ne(AdminWebsit::getWebsitId,adminWebsit.getWebsitId())
                .and(v -> v.eq(AdminWebsit::getWebsitNumber,adminWebsit.getWebsitNumber())
                        .or()
                        .eq(AdminWebsit::getName, adminWebsit.getName())
                )
                .count();
        if(count > 0){
            throw new RemoteServiceException("部门名称或部门编号已存在");
        }

        if (StringUtil.isEmpty(adminWebsit.getCompanyId()))
            throw new RemoteServiceException("上级商家不能为空");
        AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(adminWebsit.getPayWorkerCodeId());
        AdminCompanyWechat adminCompanyWechatP = adminCompanyWechatService.getById(adminWebsit.getCompanyId());
        adminWebsit.setCompanyName(adminCompanyWechatP.getCompanyName());
        adminWebsit.setPayWorkerCodeName(adminCompanyWechat.getCompanyName());
        adminWebsit.updateById();
        //workWechatLogic.updateOrganization(adminWebsit.getWebsitId(),adminWebsit.getName(),adminWebsit.getParentId(),adminUser.getAdminCompanyWechat());

    }

    /**
     * 删除部门
     */
    @Transactional
    public void delete(String id,HttpServletRequest request) throws WxErrorException {
//s        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        //递归删除
        List<AdminWebsit> list = new ArrayList<>();
        list.addAll(this.queryAllChild(list,id));
        List<String> ids = list.stream().map(AdminWebsit::getWebsitId).collect(Collectors.toList());
        ids.add(id);
        if(ids.size() > 0) {
//            for(Long idd : ids){
//                workWechatLogic.deleteOrganization(idd,adminUser.getAdminCompanyWechat());
//            }
            adminWebsitService.lambdaUpdate().in(AdminWebsit::getWebsitId, ids).remove();
        }
    }

    /**
     * 详情
     * @param id
     */
    public AdminWebsit detail(String id){
        AdminWebsit adminWebsit = adminWebsitService.getById(id);
        return adminWebsit;
    }

    /**
     * 详情
     */
    public AdminWebsit detail(Long websitId,String corpId){
        AdminWebsit adminWebsit = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getWebsitId,websitId)
                .one();
        return adminWebsit;
    }

    /**
     * 递归查询所有数据
     */
    public List<AdminWebsit> queryAllChild(List<AdminWebsit> list,String id){
        if(id == null || id.equals("0")){
            return list;
        }
        List<AdminWebsit> adminWebsits = adminWebsitService.lambdaQuery().eq(AdminWebsit::getParentId, id).list();
        if(adminWebsits.size() == 0){
            return list;
        }
        for(AdminWebsit adminWebsit:adminWebsits){
            this.queryAllChild(list,adminWebsit.getWebsitId());
        }
        list.addAll(adminWebsits);
        return list;
    }

    /**
     * 递归组装数据
     * @param list
     * @param parentId
     * @return
     */
    private List<AdminWebsitTree> treeModule(List<AdminWebsitTree> list, String parentId,String companyId){
        //最父级资源树
        if(parentId == null || parentId.equals("0")) {
            return null;
        }
        List<AdminWebsitTree> collect = list.stream()
                .filter(e -> e.getParentId().equals(parentId) && e.getCompanyId().equals(companyId)).collect(Collectors.toList());
        if(collect.size() == 0){
            return null;
        }
        for(AdminWebsitTree bean : collect){
            bean.setChildren(this.treeModule(list, bean.getWebsitId(),bean.getCompanyId()));
        }
        return collect;
    }


    public IPage<AdminWebsitVO> list(Page page, ZfireParamBean zfireParam) {

        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        //1.组装查询条件
        FieldUtils.supplyParam(zfireParam, AdminWebsitVO.class, adminUser);

        IPage<AdminWebsitVO> adminDeptWebsitVOIPage = adminMapper.listWebsit(page, zfireParam);
        return adminDeptWebsitVOIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void importData(List<Object> objects,HttpServletRequest request) {

        List<AdminWebsit> adminWebsits = new ArrayList<>();

        for (int i = 0; i < objects.size(); i++) {
            int rowIndex = i + 2;
            List<Object> row = (List<Object>) objects.get(i);

            AdminWebsit adminWebsit = new AdminWebsit();

            AdminCompanyWechat oneP = adminCompanyWechatService.lambdaQuery()
                    .eq(AdminCompanyWechat::getCompanyName, (String) row.get(0))
                    .last("limit 1").one();


            if (oneP == null)
                throw new RemoteServiceException("第"+rowIndex+"行，找不到上级商户");

            adminWebsit.setCompanyName(oneP.getCompanyName());
            adminWebsit.setCompanyId(oneP.getCompanyWechatId());
            adminWebsit.setWebsitId((String) row.get(1));
            adminWebsit.setWebsitNumber((String) row.get(1));
            adminWebsit.setName((String) row.get(2));
            adminWebsit.setMobile((String) row.get(3));
            adminWebsit.setPerson((String) row.get(4));
            adminWebsit.setPersonMobile((String) row.get(5));

            SysDictCompany sysDictCompany = sysDictCompanyService.lambdaQuery()
                    .eq(SysDictCompany::getDictType, "WEBSIT_TYPE")
                    .eq(SysDictCompany::getDictValue, (String) row.get(6)).one();

            if (sysDictCompany == null)
                throw new RemoteServiceException("第"+rowIndex+"行，找不到店铺类型");

            adminWebsit.setType((String) row.get(6));
            adminWebsit.setTypeId(sysDictCompany.getDictCode());
            adminWebsit.setAddress((String) row.get(7));
            AdminCompanyWechat one = adminCompanyWechatService.lambdaQuery()
                    .eq(AdminCompanyWechat::getCompanyName, (String) row.get(8))
                    .last("limit 1").one();

            if (one == null)
                throw new RemoteServiceException("第"+rowIndex+"行，找不到支付商户");
            adminWebsit.setPayWorkerCodeName(one.getCompanyName());
            adminWebsit.setPayWorkerCodeId(one.getCompanyWechatId());

            String lnglat = lbsAmapLogic.getLocationByAddress(adminWebsit.getAddress());

            adminWebsit.setLng(lnglat.split(",")[0]);
            adminWebsit.setLat(lnglat.split(",")[1]);
            if (row.size() > 8) {
                if (!StringUtil.isEmpty((String) row.get(9))) {
                    adminWebsit.setIsOpen(IsYesNoEnum.YES.getKey());
                    adminWebsit.setYunAppid((String) row.get(9));
                    adminWebsit.setYunAppkey((String) row.get(10));
                    adminWebsit.setYunCompany((String) row.get(11));
                    adminWebsit.setYunNumber((String) row.get(12));
                    adminWebsit.setYunSystem((String) row.get(13));
                    adminWebsit.setYunTax((String) row.get(14));
                    adminWebsit.setYunName((String) row.get(15));
                    adminWebsit.setYunTwo((((String)row.get(16)).equals("是")) ? "YES" : "NO");
                }
            }

            adminWebsits.add(adminWebsit);

        }

        adminWebsitService.saveBatch(adminWebsits);

        for (AdminWebsit adminWebsit : adminWebsits) {

            AdminUserAddReqBean adminUserBean = new AdminUserAddReqBean();
            adminUserBean.setUserName(adminWebsit.getWebsitId());
            adminUserBean.setNickName(adminWebsit.getName());
            adminUserBean.setLinkPhone(adminWebsit.getPersonMobile());
            adminUserBean.setLinkName(adminWebsit.getPerson());
            adminUserBean.setPassword("123456");
            adminUserBean.setRoleId("1899638664615489538");
            adminUserBean.setRoleName("网点");
            adminUserBean.setWebsitId(adminWebsit.getWebsitId());
            adminUserBean.setWebsitName(adminWebsit.getName());
            adminUserBean.setCompanyId(adminWebsit.getCompanyId());
            adminUserBean.setCompanyName(adminWebsit.getCompanyName());
            adminUserBean.setAddress(adminWebsit.getAddress());
            adminUserBean.setType(2);

            List<AdminUserPermissions> adminUserPermissions = new ArrayList<>();
            AdminUserPermissions adminUserPermissions1 = new AdminUserPermissions();
            adminUserPermissions1.setAdminUserPermissionsId(adminWebsit.getWebsitId());
            adminUserPermissions1.setIsDept(false);
            adminUserPermissions.add(adminUserPermissions1);

            adminUserBean.setPermissions(adminUserPermissions);
            adminUserLogic.save(adminUserBean, request);
        }
    }
}
