package com.pj.tb_people;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.cglib.CglibUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.api.client.admin.AdminInterface;
import com.pj.api.consts.FeignFactory;
import com.pj.api.dto.*;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.dto.PCLoginUserInfo;
import com.pj.current.satoken.StpUserUtil;
import com.pj.enummj.*;
import com.pj.tb_group.TbGroup;
import com.pj.tb_group.TbGroupMapper;
import com.pj.tb_order.TbOrder;
import com.pj.tb_order.TbOrderMapper;
import com.pj.tb_order_people_confirm.TbOrderPeopleConfirm;
import com.pj.tb_order_people_confirm.TbOrderPeopleConfirmMapper;
import com.pj.tb_people.dto.LeaveGroupDto;
import com.pj.tb_people.dto.StartStopDto;
import com.pj.tb_people.vo.ApplyPeopleVo;
import com.pj.tb_people.vo.BindShopVO;
import com.pj.tb_people.vo.EditPhoneVO;
import com.pj.tb_shop.TbShop;
import com.pj.tb_shop.TbShopMapper;
import com.pj.tb_shop.TbShopService;
import com.pj.tb_trade_area.TbTradeArea;
import com.pj.tb_trade_area.TbTradeAreaService;
import com.pj.utils.sg.AjaxError;
import com.pj.utils.sg.AjaxJson;
import com.pj.utils.so.SoMap;
import com.tencentcloudapi.live.v20180801.models.PublishTime;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.swing.filechooser.FileSystemView;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Service: tb_people -- 边民
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class TbPeopleService extends ServiceImpl<TbPeopleMapper, TbPeople> implements IService<TbPeople> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbPeopleMapper tbPeopleMapper;
    @Resource
    private TbShopService tbShopService;

    @Autowired
    private MethodPeopleService methodPeopleService;

    @Autowired
    private AdminInterface adminInterface;
    /**
     * 边民确认订单
     */
    @Autowired
    private TbOrderPeopleConfirmMapper tbOrderPeopleConfirmMapper;
    /**
     * 订单对象
     */
    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    TbGroupMapper tbGroupMapper;
    @Resource
    private TbTradeAreaService tbTradeAreaService;


    /**
     * 增
     */
    void add(TbPeople t) {
        t.setCreateTime(new Date())
                .setCreateName(StpUserUtil.getPCLoginInfo().getLoginName())
                .setCreateBy(StpUserUtil.getPCLoginInfo().getLoginId());
        save(t);
    }

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

    /**
     * 移除组内边民
     */
    boolean leaveGroup(LeaveGroupDto leaveGroupDto) {
        for (Long id : leaveGroupDto.getIds()) {
            LambdaUpdateWrapper<TbPeople> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(TbPeople::getGroupId, null);
            wrapper.set(TbPeople::getGroupName, "");
            wrapper.set(TbPeople::getUpdateBy, StpUserUtil.getPCLoginInfo().getLoginId());
            wrapper.set(TbPeople::getUpdateName, StpUserUtil.getPCLoginInfo().getLoginName());
            wrapper.set(TbPeople::getUpdateTime, new Date());

            wrapper.eq(TbPeople::getGroupId, leaveGroupDto.getGroupId());
            wrapper.eq(TbPeople::getId, id);

            boolean result = update(wrapper);
            if (!result) throw new RuntimeException("边民移除出组失败！");
        }
        return true;
    }

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

    }


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

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

    /**
     * 查集合 - 查询没有进组的边民
     */
    List<TbPeople> getLeftPeople() {
        return tbPeopleMapper.getLeftPeople();
    }

    /**
     * 审核
     */
    boolean judge(TbPeople tbPeople) {
        //获取登录人
        PCLoginUserInfo appUserById = StpUserUtil.getPCLoginInfo();
        if (appUserById == null) throw new RuntimeException("当前登录人账号已失效,请重新登录~");
        String loginUser = appUserById.getLoginName();
        //获取当前被审核人的编号和审核情况
        Long currId = tbPeople.getId();
        Integer judgeStatus = tbPeople.getJudgeStatus();
        //获取被审核人
        TbPeople tbPeople1 = tbPeopleMapper.selectById(currId);
        if (tbPeople1 == null) throw new RuntimeException("审核用户不存在,请检查!");
        //判断删除状态
        Integer deleteStatus = tbPeople1.getDeleteStatus();
        if (deleteStatus == 0) throw new RuntimeException("该用户已被删除,无法进行审核");
        //设置审核状态
        tbPeople1.setJudgeStatus(judgeStatus);
        if (currId == 0) tbPeople1.setJudgeContent(tbPeople.getJudgeContent());
        //设置审核人
        tbPeople1.setPersonId(loginUser);
        //审核时间
        tbPeople1.setJudgeTime(new Date());
        //保存
        int i = tbPeopleMapper.updateById(tbPeople1);
        return i == 1;

    }

    /**
     * 启/停
     */
    boolean isLock(StartStopDto startStopDto) {
        //获取被修改用户id
        Long id = startStopDto.getId();
        //查询
        TbPeople tbPeople1 = tbPeopleMapper.selectById(id);
        if (tbPeople1 == null) throw new RuntimeException("审核用户不存在,请检查!");
        //判断删除状态
        Integer deleteStatus = tbPeople1.getDeleteStatus();
        if (deleteStatus == 0) throw new RuntimeException("该用户已被删除,无法进行启/停操作!");
        //获取启停状态
        Integer isLock = startStopDto.getIsLock();
        //设置启/停
        tbPeople1.setStatus(isLock == null || isLock.toString().trim().equals("") ? tbPeople1.getIsLock() : isLock);
        //保存结果
        int i = tbPeopleMapper.updateById(tbPeople1);
        //远程调用停用app user表中的边民账号
        int lock = adminInterface.isLock(id.toString(), People.PEOPLE_TYPE_ONE.getCode(), isLock);
        // 处理远程调用后的返回结果
        if ((lock + i) != 2) throw new RuntimeException("停用失败!");

        return i == 1 && lock == 1;
    }

    /**
     * TODO: 对接单一窗口商务端实现身份识别（预留认证接口）
     */
    void identification() {

    }

//
//	/** 边民账号停用后不能登录app */
//	void loginPeople(String userName,String password){
//
//	}

    /**
     * 边民申请加入互助组
     *
     * @author loovi
     * @date
     */
    public int applyAddGroup(Long peopleId, Long groupId) {
        // 检查是否有待通过的申请
        int res = tbPeopleMapper.checkApplyExist(peopleId);
        if (res > 0) {
            throw new RuntimeException("存在带通过的申请");
        }
        // 获取边民信息
        TbPeople tbPeople = tbPeopleMapper.selectById(peopleId);
        // 获取互助组信息
        TbGroup tbGroup = tbGroupMapper.selectById(groupId);
        // 如果互助组不存在抛出异常
        if (Objects.isNull(tbGroup)) {
            throw new RuntimeException("该互助组不存在");
        }
        // 如果互助组已删除抛出异常
        if (tbGroup.getDeleteStatus() == DeleteStatus.DELETE_STATUS_OFF.getCode()) {
            throw new RuntimeException("该互助组已被删除");
        }
        // 如果边民已加入此互助组，信息提示已加入
        if (tbPeople.getGroupId() == groupId) {
            throw new RuntimeException("您已加入该互助组");
        }
        // 如果边民没有加入任何互助组则可以申请加入
        int i = 0;
        if (Objects.isNull(tbPeople.getGroupId()) && StrUtil.isEmpty(tbPeople.getGroupName())) {
            // 将申请边民和所申请的互助组id写入申请表
            i = tbPeopleMapper.addApply(peopleId, groupId);
        } else {
            throw new RuntimeException("您已加入互助组");
        }
        return i;
    }

    /**
     * 组长获取待通过申请人列表
     *
     * @author loovi
     * @date
     */
    public AjaxJson getApplyList(SoMap so) {
        // 根据组长id获取申请该互助组的所有申请人信息
        List<TbPeople> list = tbPeopleMapper.getApplyList(so.startPage());
        List<ApplyPeopleVo> resList = CglibUtil.copyList(list, ApplyPeopleVo::new);
        return AjaxJson.getPageData(so.getDataCount(), resList);
    }

    /**
     * 组长批准是否同意加入申请
     *
     * @author loovi
     * @date
     */
    public int passApply(Long groupId, Long peopleId, int approve) {
        // 组长不同意申请
        if (approve == 2) {
            int i = tbPeopleMapper.updateApplyStatus(approve, peopleId);
            return i;
        }
        // 组长同意申请
        // 获取申请人信息
        TbPeople tbPeople = tbPeopleMapper.selectById(peopleId);
        // 用户不存在抛异常
        if (Objects.isNull(tbPeople)) {
            throw new RuntimeException("用户不存在");
        }
        // 用户被锁定抛异常
        if (tbPeople.getIsLock() == IsLock.IS_LOCK_OFF.getCode()) {
            throw new RuntimeException("用户已被锁定");
        }
        // 用户已删除抛异常
        if (tbPeople.getIsLock() == DeleteStatus.DELETE_STATUS_OFF.getCode()) {
            throw new RuntimeException("用户已删除");
        }
        //根据互助组id查询互助组
        TbGroup tbGroup = tbGroupMapper.selectById(groupId);
        // 修改申请表状态为1通过
        tbPeopleMapper.updateApplyStatus(approve, peopleId);
        // 把互助组信息写入申请的边民表
        tbPeople.setGroupId(tbGroup.getId());
        tbPeople.setGroupName(tbGroup.getOrgName());
        int line = tbPeopleMapper.updateById(tbPeople);
        return line;
    }

    /**
     * 边民确认订单
     *
     * @param orderId 一级市场订单表ID
     */
    public boolean confirmOrder(Long orderId) {
        TbPeople tbPeople = methodPeopleService.getByAppUserFk();
        //执行确认 todo:调用人脸认证
        TbOrderPeopleConfirm tbOrderPeopleConfirm = new TbOrderPeopleConfirm();
        tbOrderPeopleConfirm.setPeopleId(tbPeople.getId());
        tbOrderPeopleConfirm.setGroupId(tbPeople.getGroupId());
        tbOrderPeopleConfirm.setOrderId(orderId);
        tbOrderPeopleConfirm.setPeopleName(tbPeople.getName());
        tbOrderPeopleConfirm.setCreateTime(new Date());
        int insert = tbOrderPeopleConfirmMapper.insert(tbOrderPeopleConfirm);
        //执行查询订单完成情况
        if (insert == 1) {
            //查询当前互市组的人数
            Integer selectCount = tbPeopleMapper.selectCount
                    (new LambdaQueryWrapper<TbPeople>()
                            .eq(TbPeople::getGroupId, tbPeople.getGroupId())
                            .eq(TbPeople::getIsLock, IsLock.IS_LOCK_ON.getCode())
                            .eq(TbPeople::getDeleteStatus, DeleteStatus.DELETE_STATUS_ON.getCode()));
            //查询已确认的边民的数量
            List<TbOrderPeopleConfirm> selectList = tbOrderPeopleConfirmMapper.selectList
                    (new LambdaQueryWrapper<TbOrderPeopleConfirm>().eq(TbOrderPeopleConfirm::getOrderId, orderId));
            //判断已确认的边民数量
            if (selectList.size() == selectCount) {
                //将订单得people_confirm修改成1 , 边民确认
                TbOrder tbOrder = tbOrderMapper.selectById(orderId);
                if (tbOrder == null) throw new RuntimeException("当前订单已被组长取消!");
                tbOrder.setPeopleConfirmStatus(ConfirmStatus.CONFIRM_STATUS_ONE.getCode());
                int updateById = tbOrderMapper.updateById(tbOrder);
                if (updateById != 1) throw new RuntimeException("执行边民确认异常!");
                //todo:发送冻结请求 -> 接收冻结请求，边民账户货款进行冻结，并给出回执
                return true;
            }
        }
        return false;
    }

    /**
     * 边民的进境申报,每个边民只负责自己的申报
     *
     * @param orderId 订单表主键
     * @return
     */
    public boolean entryDeclaration(Long orderId) {
        //todo:调用人脸识别,通过则执行下面方法,不通过直接返回false
        //获取其对象并进行判断
        TbOrder tbOrder = tbOrderMapper.selectById(orderId);
        if (tbOrder == null)
            throw new ServiceException("订单信息异常!");
        //修改订单状态
//        tbOrder.setApplyTime(new Date()); // 申报时间
        tbOrder.setPeopleConfirmStatus(ConfirmStatus.CONFIRM_STATUS_ONE.getCode()); // 默认边民确认
        tbOrder.setFinishStatus(OrderStatus.ORDER_STATUS_ONE.getCode()); // 订单状态已完成
        int update = tbOrderMapper.updateById(tbOrder);
        if (update == 1) {
            //todo: 调用航通接口,接收进境申报确认信息；并向海关进行进境申报
        }
        return update == 1;
    }

    /**
     * 边民进行互助委托申报，委
     * 托边民组长做集中进口申
     * 报，进口申报确认；
     */
    public void entrustDeclarationFromHT() {
        //todo: 8月27日 获取航通传输过来的边民委托申报(申报材料),我方app只负责给个确认委托申报的按钮给边民进行点击

        //1. 创建 [委托申报表] 和 [边民委托申报监听表] ,将航通传输过来的每个边民的申报信息逐条保存到 [边民委托申报监听表] ,监听表初始状态为[未委托]

        //2. 每个边民进入app点击确认委托申报后,将每个边民的 [委托申报监听] 状态改成[已完成委托]

        //3. 实时监听该 [委托申报表] 的需要完成的边民确认订数,如果该 [委托申报表] 需要完成的[边民确认委托]书足够,则修改委托申报表的完成状态

        //4. 如果边民委托申报全部完成,则将进口确认申报完成状态发送至航通

    }


    /**
     * 导入
     *
     * @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 = methodPeopleService.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) {
            // 获取当前用户的桌面路径
            FileSystemView fileSystemView = FileSystemView.getFileSystemView();
            filepath = fileSystemView.getHomeDirectory().getPath();
        }
        filepath = filepath + "\\边民数据表_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".xlsx";
        //根据需求查询数据
        List<TbPeople> selectedList = tbPeopleMapper.selectList(new LambdaQueryWrapper<TbPeople>().eq(StringUtils.isNoneBlank(keyword), TbPeople::getName, 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("姓名");
        row.createCell(2).setCellValue("边民号");
        row.createCell(3).setCellValue("性别");
        row.createCell(4).setCellValue("年龄");
        row.createCell(5).setCellValue("身份证");
        row.createCell(6).setCellValue("身份证复印件");
        row.createCell(7).setCellValue("手机号码");
        row.createCell(8).setCellValue("银行编号");
        row.createCell(9).setCellValue("银行卡号");
        row.createCell(10).setCellValue("银行名称");
        row.createCell(11).setCellValue("所属互助组");
        row.createCell(12).setCellValue("互助组名称");
        row.createCell(13).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("地址ID");
        row.createCell(20).setCellValue("详细地址");
        row.createCell(21).setCellValue("是否锁定");
        row.createCell(22).setCellValue("当天剩余额度");
        row.createCell(23).setCellValue("judge_status");
        row.createCell(24).setCellValue("judge_content");
        row.createCell(25).setCellValue("注册时间");
        row.createCell(26).setCellValue("judge_time");
        row.createCell(27).setCellValue("person_id");
        row.createCell(28).setCellValue("创建时间");
        row.createCell(29).setCellValue("创建人编号");
        row.createCell(30).setCellValue("创建人名称");
        row.createCell(31).setCellValue("更新时间");
        row.createCell(32).setCellValue("更新人编号");
        row.createCell(33).setCellValue("更新人名称");
        row.createCell(34).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).getName() + "").equals("null") ? "" : selectedList.get(i).getName() + "");
            sheetRow.createCell(2).setCellValue((selectedList.get(i).getCode() + "").equals("null") ? "" : selectedList.get(i).getCode() + "");
            sheetRow.createCell(3).setCellValue((selectedList.get(i).getSex() + "").equals("null") ? "" : selectedList.get(i).getSex() + "");
            sheetRow.createCell(4).setCellValue((selectedList.get(i).getAge() + "").equals("null") ? "" : selectedList.get(i).getAge() + "");
            sheetRow.createCell(5).setCellValue((selectedList.get(i).getIdCard() + "").equals("null") ? "" : selectedList.get(i).getIdCard() + "");
            sheetRow.createCell(6).setCellValue((selectedList.get(i).getIdCardImg() + "").equals("null") ? "" : selectedList.get(i).getIdCardImg() + "");
            sheetRow.createCell(7).setCellValue((selectedList.get(i).getPhone() + "").equals("null") ? "" : selectedList.get(i).getPhone() + "");
            sheetRow.createCell(8).setCellValue((selectedList.get(i).getBankNo() + "").equals("null") ? "" : selectedList.get(i).getBankNo() + "");
            sheetRow.createCell(9).setCellValue((selectedList.get(i).getBankCode() + "").equals("null") ? "" : selectedList.get(i).getBankCode() + "");
            sheetRow.createCell(10).setCellValue((selectedList.get(i).getBankName() + "").equals("null") ? "" : selectedList.get(i).getBankName() + "");
            sheetRow.createCell(11).setCellValue((selectedList.get(i).getGroupId() + "").equals("null") ? "" : selectedList.get(i).getGroupId() + "");
            sheetRow.createCell(12).setCellValue((selectedList.get(i).getGroupName() + "").equals("null") ? "" : selectedList.get(i).getGroupName() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getStatus() + "").equals("null") ? "" : selectedList.get(i).getStatus() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getRole() + "").equals("null") ? "" : selectedList.get(i).getRole() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getLng() + "").equals("null") ? "" : selectedList.get(i).getLng() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getLat() + "").equals("null") ? "" : selectedList.get(i).getLat() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getLastLocation() + "").equals("null") ? "" : selectedList.get(i).getLastLocation() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getAddress() + "").equals("null") ? "" : selectedList.get(i).getAddress() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getAddressIds() + "").equals("null") ? "" : selectedList.get(i).getAddressIds() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getDetailAddress() + "").equals("null") ? "" : selectedList.get(i).getDetailAddress() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getIsLock() + "").equals("null") ? "" : selectedList.get(i).getIsLock() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getLeftPrice() + "").equals("null") ? "" : selectedList.get(i).getLeftPrice() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getJudgeStatus() + "").equals("null") ? "" : selectedList.get(i).getJudgeStatus() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getJudgeContent() + "").equals("null") ? "" : selectedList.get(i).getJudgeContent() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getRegisterTime() + "").equals("null") ? "" : selectedList.get(i).getRegisterTime() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getJudgeTime() + "").equals("null") ? "" : selectedList.get(i).getJudgeTime() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getPersonId() + "").equals("null") ? "" : selectedList.get(i).getPersonId() + "");
            //公共字段
            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 peopleDto(HtPeopleDto peopleDto) throws Exception {
        TbPeople tbPeople = this.findByIdCarNo(peopleDto.getIdCardNo());
        boolean isNew = false;
        if (tbPeople == null) {
            isNew = true;
            //创建对象
            tbPeople = new TbPeople();
        }
        //数据拷贝
        peopleDto.setId(tbPeople.getId());
        BeanUtils.copyProperties(peopleDto, tbPeople);
        tbPeople.setSex(Integer.valueOf(peopleDto.getGencd().trim()));
        tbPeople.setPhone(peopleDto.getBorderTel());
        tbPeople.setIdCard(peopleDto.getIdCardNo());
        tbPeople.setName(peopleDto.getBorderName());
        //设置基本信息
        tbPeople.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode()); // 逻辑删除,默认可用
        tbPeople.setStatus(Status.STATUS_ONE.getCode());  // 可用状态
        tbPeople.setIsLock(IsLock.IS_LOCK_ON.getCode());  // 为被锁定状态
        tbPeople.setJudgeStatus(JudgeStatus.JUDGE_STATUS_ONE.getCode()); // 默认审核通过
        TbTradeArea tbTradeArea = tbTradeAreaService.updateHandler(peopleDto.getFieldCode(), "", "");
        tbPeople.setTradeAreaId(tbTradeArea.getId());
        tbPeople.setTradeAreaName(tbTradeArea.getName());
        /**备案编号，如果为新增备案，传空值；如果为变更备案，必须传值；*/

        if (isNew) {
            tbPeople.setCreateTime(new Date()); // 创建时间
            tbPeople.setCreateName("航通"); // 创建人
            this.save(tbPeople);
        } else {
            tbPeople.setUpdateTime(new Date()); // 修改时间
            tbPeople.setUpdateName("航通"); // 修改人
            this.updateById(tbPeople);
        }
        //新增

        if (isNew) {
            //给边民生成账号
            AppUserCreateDTO createDTO = new AppUserCreateDTO();
            createDTO.setAuth("1");
            createDTO.setAuthTime(new Date());
            createDTO.setUserType(UserType.USER_TYPE_PEOPLE.getCode() + "");
            createDTO.setPhone(peopleDto.getBorderTel());
            createDTO.setName(peopleDto.getBorderName());
            createDTO.setFkId(tbPeople.getId());
            adminInterface.createAccount(createDTO);
            return true;
        } else {
            AppUserDto appUserDto = adminInterface.getByFkId(tbPeople.getId());
            if (appUserDto == null) {
                //给边民生成账号
                AppUserCreateDTO createDTO = new AppUserCreateDTO();
                createDTO.setAuth("1");
                createDTO.setAuthTime(new Date());
                createDTO.setUserType(UserType.USER_TYPE_PEOPLE.getCode() + "");
                createDTO.setPhone(peopleDto.getBorderTel());
                createDTO.setName(peopleDto.getBorderName());
                createDTO.setFkId(tbPeople.getId());
                adminInterface.createAccount(createDTO);
            } else {
                appUserDto.setPhone(peopleDto.getBorderTel());
                appUserDto.setName(peopleDto.getBorderName());
                appUserDto.setUpdateTime(new Date());
                adminInterface.saveAppUserInfo(appUserDto);
            }
        }
        return true;
    }

    /**
     * 远程调用查
     */
    PeopleDto getRpcById(Long id) {
        TbPeople byId = super.getById(id);
        PeopleDto peopleDto = new PeopleDto();
        TbGroup tbGroup = tbGroupMapper.selectById(byId.getGroupId());
        if (tbGroup!=null) {
            peopleDto.setLeaderName(tbGroup.getLeaderName());
            peopleDto.setLeaderPhone(tbGroup.getLeaderPhone());
        }
        BeanUtils.copyProperties(byId, peopleDto);
        return peopleDto;
    }


    /**
     * 查集合 远程调用
     */
    List<PeopleDto> getPeopleList(SoMap so, Long groupId) {
        so.put("groupId", groupId);
        so.put("isLock", IsLock.IS_LOCK_ON.getCode());
        so.put("deleteStatus", DeleteStatus.DELETE_STATUS_ON.getCode());
        List<TbPeople> tbPeople = tbPeopleMapper.getList(so);
        if (tbPeople.size() == 0) return null;
        //创建返回值集合
        List<PeopleDto> resultDto = new ArrayList<>();
        //遍历封装
        tbPeople.forEach(item -> {
            PeopleDto peopleDto = new PeopleDto();
            BeanUtils.copyProperties(item, peopleDto);
            resultDto.add(peopleDto);
        });
        return resultDto;
    }

    /**
     * 根据角色获取边民列表
     *
     * @param tradeAreaId
     * @param role        1边民，2组长，null ||0 全部
     * @return
     */
    public List<TbPeople> getPeopleForGroup(Long tradeAreaId, Integer role) {
        QueryWrapper<TbPeople> ew = new QueryWrapper<>();
        ew.lambda().eq(TbPeople::getTradeAreaId, tradeAreaId)
                .eq(role != null && role > 0, TbPeople::getRole, role);
        return list(ew);
    }

    /**
     * 根据航通边民备案编号
     */
    public AppUserDto getAppUserByBorderPutrecNo(String borderPutrecNo) {
        //todo: 此接口为航通间接调用,当我们手动禁用appUser或people时能进行获取使用?  查询条件当前仅使用航通主键
        List<TbPeople> peopleList = tbPeopleMapper.selectList(new LambdaQueryWrapper<TbPeople>().eq(TbPeople::getPutrecNo, borderPutrecNo));
        if (peopleList.size() == 1) {
            AppUserDto appUserById = adminInterface.getAppUserById(peopleList.get(0).getId());
            //返回
            return appUserById;
        }
        //返回
        return null;
    }

    public List<TbPeople> getMemberListByGroupId(SoMap startPage) {
        return tbPeopleMapper.getMemberListByGroupId(startPage);
    }

    public List<TbPeople> getMemberListByLeaderId(SoMap startPage) {
        return tbPeopleMapper.getMemberListByLeaderId(startPage);
    }

    public TbPeople findByIdCarNo(String idNo) {
        QueryWrapper<TbPeople> ew = new QueryWrapper<>();
        ew.lambda().eq(TbPeople::getIdCard, idNo);
        List<TbPeople> list = list(ew);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 边民保存银行卡信息
     */
    public boolean saveBankByPeople(Long id, String bankNo, String bankAccount,String bankName) {
        LambdaUpdateWrapper<TbPeople> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TbPeople::getBankNo, bankNo);
        wrapper.set(TbPeople::getBankName, bankName);
        wrapper.set(TbPeople::getBankCode, bankAccount);
        wrapper.eq(TbPeople::getId, id);

        return update(wrapper);
    }

    /**
     * 根据边民姓名与身份证号查询边民是否存在
     */
    public boolean getByidCard(String name, String idCard) {
        LambdaQueryWrapper<TbPeople> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbPeople::getIdCard, idCard);
        wrapper.eq(TbPeople::getName, name);

        List<TbPeople> list = this.list(wrapper);
        return list.size() > 0;
    }

    /**
     * 边民备案验证查询-银行回复新开户或变更数据
     */
    public boolean updateBySXB005(BankInfoDto bankInfoDto) {
        LambdaUpdateWrapper<TbPeople> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TbPeople::getPhone, bankInfoDto.getTel());
        wrapper.set(TbPeople::getBankNo, bankInfoDto.getPayBankCode());
        wrapper.set(TbPeople::getBankCode, bankInfoDto.getAccount());
        wrapper.set(TbPeople::getPapersType, bankInfoDto.getPapersType());
        wrapper.set(TbPeople::getNationality, bankInfoDto.getNationality());

        wrapper.eq(TbPeople::getIdCard, bankInfoDto.getPapersNo());
        wrapper.eq(TbPeople::getName, bankInfoDto.getName());

        boolean update = update(wrapper);
        return update;
    }

    public void bindShop(BindShopVO t) {
        List<TbPeople> list = new ArrayList<>();
        StrUtil.split(t.getIds(), ",")
                .forEach(id -> {
                    TbPeople db = this.getById(id);
                    if (db != null) {
                        TbShop tbShop = tbShopService.getById(t.getShopId());
                        db.setShopId(t.getShopId()).setShopName(tbShop.getShopName());
                        list.add(db);

                    }
                });
        this.updateBatchById(list);
        BindShopDTO bindShopDTO = new BindShopDTO();
        bindShopDTO.setBindShop(2);
        bindShopDTO.setIds(t.getIds());
        FeignFactory.adminInterface.changeBindShopStatus(bindShopDTO);
    }

    public void removeBind(String id) {
        LambdaUpdateWrapper<TbPeople> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TbPeople::getShopId, null);
        wrapper.set(TbPeople::getShopName, null);
        wrapper.eq(TbPeople::getId, id);
        this.update(wrapper);
        BindShopDTO bindShopDTO = new BindShopDTO();
        bindShopDTO.setBindShop(1);
        bindShopDTO.setIds(id);
        FeignFactory.adminInterface.changeBindShopStatus(bindShopDTO);
    }

    public void editPhone(EditPhoneVO editPhoneVO) {
        String phone = editPhoneVO.getPhone();
        TbPeople tbPeople = getById(editPhoneVO.getId());
        if (tbPeople == null) {
            throw new ServiceException("该边民不存在");
        }
        AppUserDto oldUser = FeignFactory.adminInterface.findUserByPhone(tbPeople.getPhone());
        //账号不存在或者存在但不是自己的，则新增
        if (oldUser == null || !StrUtil.equals(oldUser.getName(), tbPeople.getName())) {
            AppUserCreateDTO appUserCreateDTO = new AppUserCreateDTO();
            appUserCreateDTO.setAuth("1");
            appUserCreateDTO.setPhone(phone);
            appUserCreateDTO.setName(tbPeople.getName());
            appUserCreateDTO.setFkId(tbPeople.getId());
            appUserCreateDTO.setUserType(UserType.USER_TYPE_PEOPLE.getCode() + "");
            log.info("create user :{}", JSONUtil.toJsonStr(appUserCreateDTO));
            FeignFactory.adminInterface.createAccount(appUserCreateDTO);
        } else {
            //存在，检查下是否冲突
            AppUserDto checkUser = FeignFactory.adminInterface.findUserByPhone(editPhoneVO.getPhone());
            if (checkUser != null && !Objects.equals(checkUser.getFkId(), tbPeople.getId())) {
                throw new AjaxError("手机已被【" + checkUser.getName() + "】占用");
            }
            UpdateAccountDTO updateAccountDTO = new UpdateAccountDTO();
            updateAccountDTO.setPhone(phone);
            updateAccountDTO.setId(oldUser.getId());
            FeignFactory.adminInterface.updateAccount(updateAccountDTO);
        }
        tbPeople.setPhone(phone);
        this.updateById(tbPeople);


    }


}
