package com.pj.tb_enterprise;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.DistrictDTO;
import com.pj.api.dto.EnterpriseAuditDto;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.current.satoken.StpAPPUserUtil;
import com.pj.current.satoken.StpUserUtil;
import com.pj.enummj.*;
import com.pj.tb_enterprise.dto.EnterpriseDto;
import com.pj.tb_enterprise.vo.OrdersVo;
import com.pj.tb_order.TbOrder;
import com.pj.tb_order.TbOrderMapper;
import com.pj.utils.sg.AjaxError;
import com.pj.utils.so.SoMap;
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.swing.filechooser.FileSystemView;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * Service: tb_enterprise -- 商家
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbEnterpriseService extends ServiceImpl<TbEnterpriseMapper, TbEnterprise> implements IService<TbEnterprise> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbEnterpriseMapper tbEnterpriseMapper;
    /**
     * rpc远程调用
     */
    @Autowired
    AdminInterface adminInterface;

    /**
     * 订单表mapper
     */
    @Autowired
    private TbOrderMapper tbOrderMapper;

    /**
     * 非事务方法调用事务方法需要代理对象
     */
    @Autowired
    private MethodEnterpriseService methodEnterpriseService;

    /**
     * 增
     */
    void add(TbEnterprise t) {
        List<DistrictDTO> districtDTOS = FeignFactory.adminInterface.getDistrictList(t.getAddressIds());
        t.setAddress(districtDTOS.stream().map(DistrictDTO::getDistrict).collect(Collectors.joining())).setCreateTime(new Date()).setCreateName(StpUserUtil.getPCLoginInfo().getLoginName());
        save(t);
    }

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

    /**
     * 改
     */
    void update(TbEnterprise t) {
        List<DistrictDTO> districtDTOS = FeignFactory.adminInterface.getDistrictList(t.getAddressIds());
        t.setAddress(districtDTOS.stream().map(DistrictDTO::getDistrict).collect(Collectors.joining())).setCreateTime(new Date()).setCreateName(StpUserUtil.getPCLoginInfo().getLoginName());
        updateById(t);

    }

    /**
     * 查
     */
    TbEnterprise getById(Long id) {
        return super.getById(id);
    }

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


    public int isLock(TbEnterpriseDto tbEnterpriseDto) {
        // 获取当前登录用户id
        Long loginId = StpUserUtil.getLoginIdAsLong();
        // 根据id获取商户
        TbEnterprise tbEnterprise = tbEnterpriseMapper.selectById(tbEnterpriseDto.getId());
        // 如果商户不存在则抛出异常
        if (Objects.isNull(tbEnterprise)) {
            throw new RuntimeException("该商户不存在");
        }
        BeanUtils.copyProperties(tbEnterpriseDto, tbEnterprise);
        // 写入更新者id
        tbEnterprise.setUpdateBy(String.valueOf(loginId));
        // 更新商户锁定状态
        int line = tbEnterpriseMapper.updateById(tbEnterprise);
        //获取商户锁定状态
        int isLock = tbEnterprise.getIsLock();
        // 如果商户被锁住则禁止app端登录
        adminInterface.isLock(String.valueOf(tbEnterprise.getId()), People.PEOPLE_TYPE_TWO.getCode(), isLock);

        return line;
    }

    public TbEnterprise selectByCreateBy() {
        return tbEnterpriseMapper.selectByCreateBy("" + StpAPPUserUtil.getAPPLoginInfo().getLoginId());
    }

    /**
     * 商家认证
     *
     * @return
     */
    boolean identification(EnterpriseDto dto) {
        TbEnterprise enterprise = tbEnterpriseMapper.selectByCreateBy("" + StpAPPUserUtil.getAPPLoginInfo().getLoginId());
        dto.setJudgeStatus(0);
        String contact = enterprise != null ? enterprise.getOwnerTel() : "";
        String idCard = enterprise != null ? enterprise.getIdCard() : "";
        //手机号查重
        if (!contact.equals(dto.getContact()) && tbEnterpriseMapper.selectList(new LambdaQueryWrapper<TbEnterprise>().eq(TbEnterprise::getOwnerTel, dto.getContact()).eq(TbEnterprise::getDeleteStatus, DeleteStatus.DELETE_STATUS_ON.getCode())).size() != 0) {
            throw new RuntimeException("当前手机号已被认证!");
        }
        //身份证号查重
        if (!idCard.equals(dto.getIdCard()) && tbEnterpriseMapper.selectList(new LambdaQueryWrapper<TbEnterprise>().eq(TbEnterprise::getIdCard, dto.getIdCard()).eq(TbEnterprise::getDeleteStatus, DeleteStatus.DELETE_STATUS_ON.getCode())).size() != 0) {
            throw new RuntimeException("当前身份证号已被认证!");
        }
        if (enterprise == null) {
            enterprise = new TbEnterprise();
            BeanUtils.copyProperties(dto, enterprise);
            enterprise.setCreateTime(new Date());
            enterprise.setCreateBy("" + StpAPPUserUtil.getAPPLoginInfo().getLoginId());
            enterprise.setDeleteStatus(Long.valueOf(DeleteStatus.DELETE_STATUS_ON.getCode()));
            return save(enterprise);
        }
        dto.setId(enterprise.getId());
        BeanUtils.copyProperties(dto, enterprise);
        return updateById(enterprise);
    }


    /**
     * 导入
     *
     * @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 = methodEnterpriseService.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<TbEnterprise> selectedList = tbEnterpriseMapper.selectList(new LambdaQueryWrapper<TbEnterprise>().eq(StringUtils.isNoneBlank(keyword), TbEnterprise::getOwnerName, 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("地址ID集合");
        row.createCell(15).setCellValue("地址");
        row.createCell(16).setCellValue("agreement");
        row.createCell(17).setCellValue("judge_status");
        row.createCell(18).setCellValue("judge_content");
        row.createCell(19).setCellValue("judge_time");
        row.createCell(20).setCellValue("注册时间");
        row.createCell(21).setCellValue("人物编号");
        row.createCell(22).setCellValue("创建时间");
        row.createCell(23).setCellValue("创建人编号");
        row.createCell(24).setCellValue("创建人名称");
        row.createCell(25).setCellValue("更新时间");
        row.createCell(26).setCellValue("更新人编号");
        row.createCell(27).setCellValue("更新人名称");
        row.createCell(28).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).getOwnerName() + "").equals("null") ? "" : selectedList.get(i).getOwnerName() + "");
            sheetRow.createCell(2).setCellValue((selectedList.get(i).getNationality() + "").equals("null") ? "" : selectedList.get(i).getNationality() + "");
            sheetRow.createCell(3).setCellValue((selectedList.get(i).getType() + "").equals("null") ? "" : selectedList.get(i).getType() + "");
            sheetRow.createCell(4).setCellValue((selectedList.get(i).getLegalPerson() + "").equals("null") ? "" : selectedList.get(i).getLegalPerson() + "");
            sheetRow.createCell(5).setCellValue((selectedList.get(i).getIdCard() + "").equals("null") ? "" : selectedList.get(i).getIdCard() + "");
            sheetRow.createCell(6).setCellValue((selectedList.get(i).getOwnerTel() + "").equals("null") ? "" : selectedList.get(i).getOwnerTel() + "");
            sheetRow.createCell(7).setCellValue((selectedList.get(i).getBusinessLicense() + "").equals("null") ? "" : selectedList.get(i).getBusinessLicense() + "");
            sheetRow.createCell(8).setCellValue((selectedList.get(i).getShopId() + "").equals("null") ? "" : selectedList.get(i).getShopId() + "");
            sheetRow.createCell(9).setCellValue((selectedList.get(i).getShopName() + "").equals("null") ? "" : selectedList.get(i).getShopName() + "");
            sheetRow.createCell(10).setCellValue((selectedList.get(i).getBankNo() + "").equals("null") ? "" : selectedList.get(i).getBankNo() + "");
            sheetRow.createCell(11).setCellValue((selectedList.get(i).getBank() + "").equals("null") ? "" : selectedList.get(i).getBank() + "");
            sheetRow.createCell(12).setCellValue((selectedList.get(i).getBankAccount() + "").equals("null") ? "" : selectedList.get(i).getBankAccount() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getDutyParagraph() + "").equals("null") ? "" : selectedList.get(i).getDutyParagraph() + "");
            sheetRow.createCell(14).setCellValue((selectedList.get(i).getAddressIds() + "").equals("null") ? "" : selectedList.get(i).getAddressIds() + "");
            sheetRow.createCell(15).setCellValue((selectedList.get(i).getAddress() + "").equals("null") ? "" : selectedList.get(i).getAddress() + "");
            sheetRow.createCell(16).setCellValue((selectedList.get(i).getAgreement() + "").equals("null") ? "" : selectedList.get(i).getAgreement() + "");
            sheetRow.createCell(17).setCellValue((selectedList.get(i).getJudgeStatus() + "").equals("null") ? "" : selectedList.get(i).getJudgeStatus() + "");
            sheetRow.createCell(18).setCellValue((selectedList.get(i).getJudgeContent() + "").equals("null") ? "" : selectedList.get(i).getJudgeContent() + "");
            sheetRow.createCell(19).setCellValue((selectedList.get(i).getJudgeTime() + "").equals("null") ? "" : selectedList.get(i).getJudgeTime() + "");
            sheetRow.createCell(20).setCellValue((selectedList.get(i).getRegisterTime() + "").equals("null") ? "" : selectedList.get(i).getRegisterTime() + "");
//			sheetRow.createCell(21).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 enterpriseDto(com.pj.api.dto.EnterpriseDto enterpriseDto) {
        TbEnterprise tbEnterprise = new TbEnterprise();
        BeanUtils.copyProperties(enterpriseDto, tbEnterprise);
        boolean save = this.save(tbEnterprise);
        return save;
    }

    @Transactional
    public boolean audit(Long id, Integer judgeStatus, String judgeContent) {
        TbEnterprise tbEnterprise = this.getById(id);
        if (tbEnterprise == null) {
            throw new AjaxError("商户不存在");
        }
        String name = StpUserUtil.getLoginName();
        tbEnterprise.setJudgeStatus(judgeStatus).setJudgeContent(judgeContent).setJudgeTime(new Date()).setJudgeBy(name);
        if (judgeStatus == 1) {
            EnterpriseAuditDto auditDto = new EnterpriseAuditDto();
            auditDto.setAuth("1");
            auditDto.setFkId(id);
            auditDto.setId(Long.parseLong(tbEnterprise.getCreateBy()));
            System.out.println("商户审核:"+auditDto.getId());
            boolean row = adminInterface.audit(auditDto);
            if (row) {
                this.updateById(tbEnterprise);
            }
            return row;
        }
        return false;
    }

    /**
     * 批量审核
     *
     * @param ids
     * @param judgeStatus
     * @param judgeContent
     */
    public void auditBatch(List<Long> ids, Integer judgeStatus, String judgeContent) {
        if (ids.isEmpty()) {
            throw new AjaxError("必要参数不能为空");
        }
        List<TbEnterprise> list = listByIds(ids);
        String name = StpUserUtil.getLoginName();
        list.forEach(tbEnterprise -> {
            tbEnterprise.setJudgeStatus(judgeStatus).setJudgeContent(judgeContent).setJudgeTime(new Date()).setJudgeBy(name);
        });
        this.updateBatchById(list);
    }

    /**
     * 远程调用:根据ID获取一级市场商户
     */
    com.pj.api.dto.EnterpriseDto getEnterpriseById(Long id) {
        TbEnterprise enterprise = tbEnterpriseMapper.selectById(id);
        com.pj.api.dto.EnterpriseDto enterpriseDto = new com.pj.api.dto.EnterpriseDto();
        BeanUtils.copyProperties(enterprise, enterpriseDto);
        return enterpriseDto;
    }

    /**
     * 远程调用: 根据电话查询外籍商户
     */
    public List<com.pj.api.dto.EnterpriseDto> getEnterpriseDtoListByPhone(String phone){
        List<TbEnterprise> tbEnterprises = tbEnterpriseMapper.selectList(new LambdaQueryWrapper<TbEnterprise>()
                .eq(TbEnterprise::getOwnerTel, phone)
//                .eq(TbEnterprise::getIsLock, IsLock.IS_LOCK_ON.getCode())
//                .eq(TbEnterprise::getDeleteStatus,DeleteStatus.DELETE_STATUS_ON.getCode())
//                .eq(TbEnterprise::getJudgeStatus, JudgeStatus.JUDGE_STATUS_ONE.getCode())
//                .eq(TbEnterprise::getEDStatus, HtDeleteStatus.DELETE_STATUS_ONE.getCode())
                );
        List<com.pj.api.dto.EnterpriseDto> result = new ArrayList<>();
        if(tbEnterprises.size() > 0){
            tbEnterprises.forEach(item -> {
                com.pj.api.dto.EnterpriseDto enterpriseDto = new com.pj.api.dto.EnterpriseDto();
                BeanUtils.copyProperties(item,enterpriseDto);
                result.add(enterpriseDto);
            });
        }
        return result;
    }

    public TbEnterprise findBydutyParagraph(String shopSccd) {
        QueryWrapper<TbEnterprise>ew=new QueryWrapper<>();
        ew.lambda().eq(TbEnterprise::getDutyParagraph,shopSccd);
        List<TbEnterprise> list=list(ew);
        return list.isEmpty()?null:list.get(0);
    }
}
