package com.pj.tb_group;

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pj.api.client.admin.AdminInterface;
import com.pj.api.dto.*;
import com.pj.current.satoken.StpUserUtil;
import com.pj.enummj.DeleteStatus;
import com.pj.enummj.IsLock;
import com.pj.tb_people.TbPeople;
import com.pj.tb_people.TbPeopleMapper;
import com.pj.tb_people.TbPeopleService;
import com.pj.tb_trade_area.TbTradeArea;
import com.pj.tb_trade_area.TbTradeAreaService;
import com.pj.utils.so.SoMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.pj.utils.sg.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.swing.filechooser.FileSystemView;

/**
 * Service: tb_group -- 互助组
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class TbGroupService extends ServiceImpl<TbGroupMapper, TbGroup> implements IService<TbGroup> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbGroupMapper tbGroupMapper;
    @Autowired
    TbPeopleService tbPeopleService;
    @Autowired
    TbPeopleMapper tbPeopleMapper;

    @Autowired
    private MethodGroupService methodGroupService;

    @Resource
    private TbTradeAreaService tbTradeAreaService;
    @Autowired
    private AdminInterface adminInterface;

    /**
     * 增
     */
    void add(TbGroup t) {
        t.setCreateTime(new Date())
                .setCreateName(StpUserUtil.getPCLoginInfo().getLoginName())
                .setCreateBy(Long.valueOf(StpUserUtil.getPCLoginInfo().getLoginId()))
                .setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode())
                .setIsLock(IsLock.IS_LOCK_ON.getCode());
        save(t);
    }

    /**
     * 删
     */
    void delete(Long id) {
        removeById(id);
    }

    /**
     * 改
     */
    void update(TbGroup t) {
        t.setUpdateTime(new Date())
                .setUpdateName(StpUserUtil.getPCLoginInfo().getLoginName())
                .setUpdateBy(Long.valueOf(StpUserUtil.getPCLoginInfo().getLoginId()));
        updateById(t);

    }

    /**
     * 查
     */
    TbGroup getById(String id) {
        return super.getById(id);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    List<TbGroup> getList(SoMap so) {
        return tbGroupMapper.getList(so);
    }

    public int setLeader(Long groupId, Long leaderId) {
        // 获取当前登录用户id
        Long loginId = StpUserUtil.getLoginIdAsLong();
        // 获取互助组信息
        TbGroup tbGroup = tbGroupMapper.selectById(groupId);
        // 获取边民信息
        TbPeople tbPeople = tbPeopleService.getById(leaderId);
        // 如果互助组不存在则抛异常
        if (Objects.isNull(tbGroup)) {
            throw new RuntimeException("该互助组不存在");
        }
        // 如果边民不存在
        if (Objects.isNull(tbPeople)) {
            throw new RuntimeException("该用户不存在");
        }
        // 如果互助组被锁定则抛异常
        if (tbGroup.getIsLock() == 1) {
            throw new RuntimeException("该互助组已被锁定");
        }
        // 如果边民不存在则抛异常
        if (tbPeople.getIsLock() == 1) {
            throw new RuntimeException("该用户已被锁定");
        }
        // 设置互助组组长
        tbGroup.setLeaderId(tbPeople.getId());
        tbGroup.setLeaderName(tbPeople.getName());
        tbGroup.setLeaderPhone(tbPeople.getPhone());
        // 写入更新者id
        tbGroup.setUpdateBy(loginId);
        // 更新互助组
        int line = tbGroupMapper.updateById(tbGroup);
        return line;
    }

    public int AddGroupPeople(Long groupId, Long[] peopleIds) {
        // 获取当前登录用户id
//		Long loginId = StpUserUtil.getLoginIdAsLong();
        int line = 0;
        // 获取互助组信息
        TbGroup tbGroup = tbGroupMapper.selectById(groupId);
        // 如果互助组不存在则抛异常
        if (Objects.isNull(tbGroup)) {
            throw new RuntimeException("该互助组不存在");
        }
        // 如果互助组被锁定则抛异常
        if (tbGroup.getIsLock() == 1) {
            throw new RuntimeException("该互助组已被锁定");
        }
        // 如果互助组被删除则抛异常
        if (tbGroup.getDeleteStatus() == 1) {
            throw new RuntimeException("该互助组已被删除");
        }
        List<Long> list = Arrays.asList(peopleIds);
        // 把互助组信息写入边民表
        for (Long peopleId : list) {
            TbPeople tbPeople = tbPeopleMapper.selectById(peopleId);
            tbPeople.setGroupId(tbGroup.getId());
            tbPeople.setGroupName(tbGroup.getOrgName());
            // 写入更新者id
//			tbPeople.setUpdateBy(String.valueOf(loginId));
            int i = tbPeopleMapper.updateById(tbPeople);
            line = i + 1;
        }
        return line;

    }

    public int DelGroupPeople(Long groupId, Long[] peopleIds) {

        // 获取当前登录用户id
        Long loginId = StpUserUtil.getLoginIdAsLong();
        int line = 0;
        // 获取互助组信息
        TbGroup tbGroup = tbGroupMapper.selectById(groupId);
        // 如果互助组不存在则抛异常
        if (Objects.isNull(tbGroup)) {
            throw new RuntimeException("该互助组不存在");
        }
        // 如果互助组被锁定则抛异常
        if (tbGroup.getIsLock() == 1) {
            throw new RuntimeException("该互助组已被锁定");
        }
        // 如果互助组被删除则抛异常
        if (tbGroup.getDeleteStatus() == 1) {
            throw new RuntimeException("该互助组已被删除");
        }
        List<Long> list = Arrays.asList(peopleIds);
        // 把边民表互助组信息置空
        for (Long peopleId : list) {
            TbPeople tbPeople = tbPeopleMapper.selectById(peopleId);
            tbPeople.setGroupId(0L);
            tbPeople.setGroupName("");
            // 写入更新者id
            tbPeople.setUpdateBy(String.valueOf(loginId));
            int i = tbPeopleMapper.updateById(tbPeople);
            line = i + 1;
        }
        return line;
    }

    public int isLock(TbGroupDto tbGroupDto) {
        // 获取当前登录用户id
        Long loginId = StpUserUtil.getLoginIdAsLong();
        // 获取互助组信息
        TbGroup tbGroup = tbGroupMapper.selectById(tbGroupDto.getId());
        // 如果互助组不存在则抛异常
        if (Objects.isNull(tbGroup)) {
            throw new RuntimeException("该互助组不存在");
        }
        // 如果互助组被删除则抛异常
        if (tbGroup.getDeleteStatus() == 1) {
            throw new RuntimeException("该互助组已被删除");
        }
        BeanUtils.copyProperties(tbGroupDto, tbGroup);
        // 写入更新者id
        tbGroup.setUpdateBy(loginId);
        // 更新互助组信息
        int line = tbGroupMapper.updateById(tbGroup);
        return line;
    }

    /**
     * 根据互助组id查看组内成员
     *
     * @author loovi
     * @date
     */
    public AjaxJson getMemberListByGroupId(Long id) {
        SoMap so = SoMap.getRequestSoMap();
        so.set("groupId", id);
        List<TbPeople> list = tbPeopleMapper.getMemberListByGroupId(so.startPage());
        return AjaxJson.getPageData(so.getDataCount(), list);
    }

    /**
     * 组长查看互助组内成员
     *
     * @author loovi
     * @date
     */
    public AjaxJson getMemberListByLeaderId(Long id) {
        SoMap so = SoMap.getRequestSoMap();
        so.set("leaderId", id);
        List<TbPeople> list = tbPeopleMapper.getMemberListByLeaderId(so.startPage());
        return AjaxJson.getPageData(so.getDataCount(), list);
    }

    /**
     * 导入
     *
     * @param file excel文件
     * @return
     * @throws IOException
     */
    public String importData(MultipartFile file) throws IOException {
        System.out.println("\n开始执行文件上传....\n");

        //判空
        if (file.isEmpty()) return "文件为空,无法执行上传...";
        //获取文件上传数据
        HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
        //获取第一页sheet
        HSSFSheet sheet = wb.getSheetAt(0);
        //定义计数器
        int count = 0;
        //定义行对象
        HSSFRow row = null;
        //解析数据封装到集合
        count = methodGroupService.importMethod(row, sheet, count);
        wb.close();
        System.out.println("\n文件上传完成,共上传 " + count + "条 " + "数据...\n");
        return "上传完成,共上传" + count + "条" + "数据。";
    }

    /**
     * 导出 excel文件
     *
     * @param keyword
     * @return
     */
    public String outportExcel(String keyword, String filepath) throws IOException {
        System.out.println("\n开始执行文件导出....\n");
        //导出的文件的路径
        if (filepath == null || filepath.trim().equals("")) {
            // 获取当前用户的桌面路径
            FileSystemView fileSystemView = FileSystemView.getFileSystemView();
            filepath = fileSystemView.getHomeDirectory().getPath();
        }
        filepath = filepath + "\\互助组数据表_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".xlsx";
        //根据需求查询数据
        List<TbGroup> selectedList = tbGroupMapper.selectList(new LambdaQueryWrapper<TbGroup>().eq(StringUtils.isNoneBlank(keyword), TbGroup::getOrgName, keyword));
        if (selectedList.size() == 0) return "没有可导出的数据。";
        //建立excel对象封装数据
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建excel表格右下角的sheet页名称
        HSSFSheet sheet = workbook.createSheet("1");
        //创建表头
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("IDs");
        row.createCell(2).setCellValue("地址");
        row.createCell(3).setCellValue("详细地址");
        row.createCell(4).setCellValue("组名称");
        row.createCell(5).setCellValue("组长ID");
        row.createCell(6).setCellValue("组长名");
        row.createCell(7).setCellValue("组长电话");
        row.createCell(8).setCellValue("编码");
        row.createCell(9).setCellValue("当天该组剩余额度");

        row.createCell(14).setCellValue("创建时间");
        row.createCell(15).setCellValue("创建人编号");
        row.createCell(16).setCellValue("创建人名称");
        row.createCell(17).setCellValue("更新时间");
        row.createCell(18).setCellValue("更新人编号");
        row.createCell(19).setCellValue("更新人名称");
        row.createCell(20).setCellValue("删除状态");

        //定义计数器
        int count = 0;
        //遍历集合
        for (int i = 0; i < selectedList.size(); i++) {
            HSSFRow sheetRow = sheet.createRow(sheet.getLastRowNum() + 1);
            sheetRow.createCell(0).setCellValue(i + 1);
            sheetRow.createCell(1).setCellValue((selectedList.get(i).getAddressIds() + "").equals("null") ? "" : selectedList.get(i).getAddressIds() + "");
            sheetRow.createCell(2).setCellValue((selectedList.get(i).getAddress() + "").equals("null") ? "" : selectedList.get(i).getAddress() + "");
            sheetRow.createCell(3).setCellValue((selectedList.get(i).getDetailAddress() + "").equals("null") ? "" : selectedList.get(i).getDetailAddress() + "");
            sheetRow.createCell(4).setCellValue((selectedList.get(i).getOrgName() + "").equals("null") ? "" : selectedList.get(i).getOrgName() + "");
            sheetRow.createCell(5).setCellValue((selectedList.get(i).getLeaderId() + "").equals("null") ? "" : selectedList.get(i).getLeaderId() + "");
            sheetRow.createCell(6).setCellValue((selectedList.get(i).getLeaderName() + "").equals("null") ? "" : selectedList.get(i).getLeaderName() + "");
            sheetRow.createCell(7).setCellValue((selectedList.get(i).getLeaderPhone() + "").equals("null") ? "" : selectedList.get(i).getLeaderPhone() + "");
            sheetRow.createCell(8).setCellValue((selectedList.get(i).getCode() + "").equals("null") ? "" : selectedList.get(i).getCode() + "");
            sheetRow.createCell(9).setCellValue((selectedList.get(i).getLeftPrice() + "").equals("null") ? "" : selectedList.get(i).getLeftPrice() + "");

            //公共字段
            sheetRow.createCell(22).setCellValue((selectedList.get(i).getCreateTime() + "").equals("null") ? "" : selectedList.get(i).getCreateTime() + "");
            sheetRow.createCell(23).setCellValue((selectedList.get(i).getCreateBy() + "").equals("null") ? "" : selectedList.get(i).getCreateBy() + "");
            sheetRow.createCell(24).setCellValue((selectedList.get(i).getCreateName() + "").equals("null") ? "" : selectedList.get(i).getCreateName() + "");
            sheetRow.createCell(25).setCellValue((selectedList.get(i).getUpdateTime() + "").equals("null") ? "" : selectedList.get(i).getUpdateTime() + "");
            sheetRow.createCell(26).setCellValue((selectedList.get(i).getUpdateBy() + "").equals("null") ? "" : selectedList.get(i).getUpdateBy() + "");
            sheetRow.createCell(27).setCellValue((selectedList.get(i).getUpdateName() + "").equals("null") ? "" : selectedList.get(i).getUpdateName() + "");
            sheetRow.createCell(28).setCellValue((selectedList.get(i).getDeleteStatus() + "").equals("null") ? "" : selectedList.get(i).getDeleteStatus() + "");
            count += 1;
        }
        //建立输出流，输出文件
        FileOutputStream fos = new FileOutputStream(filepath);

        workbook.write(fos);
        fos.flush();
        //关闭输出流
        fos.close();
        workbook.close();
        System.out.println("\n数据导出完成!共导出 " + count + " 条数据。");
        return "数据导出完成!共导出 " + count + " 条数据。";
    }

    /**
     * 远程调用方法
     */
    public boolean groupDto(HtGroupDto groupDto) {
        log.info("还是处理互助组信息:{}",JSONUtil.toJsonStr(groupDto));
        // 边民信息表体信息
        List<BorderDTO> borderDTOList = JSONUtil.toList(groupDto.getBorderList(), BorderDTO.class);
        //互助组边民代表(组长)表体信息——>默认一个互助组只有一个组长
        List<DclBorderList> dclBorderList = JSONUtil.toList(groupDto.getDclBorderList(), DclBorderList.class);

        TbTradeArea tbTradeArea = tbTradeAreaService.updateHandler(groupDto.getFieldCode(), "", "");
        //根据登记号进行事务处理
        TbGroup tbGroup = this.findByAreaCodeAndSeqCode(tbTradeArea.getId(), groupDto.getShopsSccd());
        if(tbGroup != null) {
            //清空原互助组边民的组信息
            LambdaQueryWrapper<TbPeople> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TbPeople::getGroupId, tbGroup.getId());
            List<TbPeople> peopleList = tbPeopleMapper.selectList(wrapper);

            for (TbPeople people:peopleList) {
                people.setGroupName(null).setGroupId(null).setUpdateTime(new Date());
            }
            tbPeopleService.updateBatchById(peopleList);
            //删除原互助组
            removeById(tbGroup.getId());
        }

        //新增
        tbGroup = new TbGroup();
        BeanUtils.copyProperties(groupDto, tbGroup);
        tbGroup.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());
        tbGroup.setCreateTime(new Date())
                .setTradeAreaId(tbTradeArea.getId())
                .setTradeAreaName(tbTradeArea.getName());
        this.save(tbGroup);


        for (BorderDTO borderDTO : borderDTOList) {
            TbPeople tbPeople = tbPeopleService.findByIdCarNo(borderDTO.getIdCardNo());
            if (tbPeople == null) {
                tbPeople = new TbPeople();
            }
            //判断当前边民是否是组长
            List<DclBorderList> dclBorderList1 = dclBorderList.stream().filter(dclBorder -> dclBorder.getIdCardNo().equals(borderDTO.getIdCardNo())).collect(Collectors.toList());
            if (dclBorderList1.size() > 0) {
                tbPeople.setRole(2);//组长
            } else {
                tbPeople.setRole(1);//普通边民
            }
            tbPeople.setGroupName(tbGroup.getOrgName()).setGroupId(tbGroup.getId())
                    .setTradeAreaId(tbTradeArea.getId()).setTradeAreaName(tbTradeArea.getName()).setUpdateTime(new Date());
            tbPeopleService.saveOrUpdate(tbPeople);

            if (dclBorderList1.size() > 0) {
                AppUserDto appUser = adminInterface.getByFkId(tbPeople.getId());
                if (appUser != null) {
                    appUser.setUserType(2);
                    adminInterface.saveAppUserInfo(appUser);
                }
            }
        }

        for (DclBorderList dclBorder : dclBorderList) {
            TbPeople p = tbPeopleService.findByIdCarNo(dclBorder.getIdCardNo());
            if(p != null) {
                tbGroup.setLeaderId(p.getId()).setLeaderName(p.getName()).setLeaderPhone(p.getPhone());
                break;
            }
        }
        super.saveOrUpdate(tbGroup);

        return true;
    }

    public TbGroup findByAreaCodeAndSeqCode(Long tradeId, String shopsSccd) {
        QueryWrapper<TbGroup> ew = new QueryWrapper<>();
        ew.lambda().eq(TbGroup::getShopsSccd, shopsSccd).eq(TbGroup::getTradeAreaId, tradeId).orderByDesc(TbGroup::getCreateTime);
        List<TbGroup> list = list(ew);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 远程调用方法 获取边民组的基本信息
     */
    GroupDto getRpcById(String id) {
        TbGroup byId = super.getById(id);
        GroupDto groupDto = new GroupDto();
        BeanUtils.copyProperties(byId, groupDto);
        return groupDto;
    }

}

