package com.pj.tb_shop;

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 cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
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.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.enummj.*;
import com.pj.project4sp.SP;
import com.pj.tb_enterprise.TbEnterprise;
import com.pj.tb_enterprise.TbEnterpriseMapper;
import com.pj.tb_enterprise.TbEnterpriseService;
import com.pj.tb_people.TbPeople;
import com.pj.tb_shop.vo.ShopVo;
import com.pj.tb_trade_area.TbTradeArea;
import com.pj.tb_trade_area.TbTradeAreaService;
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 com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * Service: tb_shop -- 铺位
 *
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbShopService extends ServiceImpl<TbShopMapper, TbShop> implements IService<TbShop> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbShopMapper tbShopMapper;

    @Autowired
    private MethodShopService methodShopService;

    @Autowired
    private TbEnterpriseMapper tbEnterpriseMapper;
    @Resource
    private TbEnterpriseService tbEnterpriseService;

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

    /**
     * 增
     */
    void add(TbShop t) {
        save(t);
    }

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

    /**
     * 改
     */
    void update(TbShop t) {
        updateById(t);

    }

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

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

    /**
     * app查集合
     */
    List<ShopVo> getAppList() {
        SoMap so = new SoMap();
        so.set("deleteStatus", 1);
        List<TbShop> list = tbShopMapper.getList(so);

        List<ShopVo> shopVoList = new ArrayList<>();
        list.forEach(tbShop -> {
            ShopVo shopVo = new ShopVo();
            BeanUtils.copyProperties(tbShop, shopVo);
            shopVoList.add(shopVo);
        });
        return shopVoList;
    }

    /**
     * 导入
     *
     * @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 = methodShopService.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<TbShop> selectedList = tbShopMapper.selectList(new LambdaQueryWrapper<TbShop>().eq(StringUtils.isNoneBlank(keyword), TbShop::getShopName, 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("enterprise_id");
        row.createCell(2).setCellValue("交易地区ID");
        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(10).setCellValue("备注");
        row.createCell(11).setCellValue("enterprise_name");

        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).getEnterpriseId() + "").equals("null") ? "" : selectedList.get(i).getEnterpriseId() + "");
            sheetRow.createCell(2).setCellValue((selectedList.get(i).getTradeAreaId() + "").equals("null") ? "" : selectedList.get(i).getTradeAreaId() + "");
            sheetRow.createCell(3).setCellValue((selectedList.get(i).getTradeAreaName() + "").equals("null") ? "" : selectedList.get(i).getTradeAreaName() + "");
            sheetRow.createCell(4).setCellValue((selectedList.get(i).getAddress() + "").equals("null") ? "" : selectedList.get(i).getAddress() + "");
            sheetRow.createCell(5).setCellValue((selectedList.get(i).getAddressIds() + "").equals("null") ? "" : selectedList.get(i).getAddressIds() + "");
            sheetRow.createCell(6).setCellValue((selectedList.get(i).getShopName() + "").equals("null") ? "" : selectedList.get(i).getShopName() + "");
            sheetRow.createCell(7).setCellValue((selectedList.get(i).getShopNo() + "").equals("null") ? "" : selectedList.get(i).getShopNo() + "");
            sheetRow.createCell(8).setCellValue((selectedList.get(i).getArea() + "").equals("null") ? "" : selectedList.get(i).getArea() + "");
            sheetRow.createCell(9).setCellValue((selectedList.get(i).getStatus() + "").equals("null") ? "" : selectedList.get(i).getStatus() + "");
            sheetRow.createCell(10).setCellValue((selectedList.get(i).getRemark() + "").equals("null") ? "" : selectedList.get(i).getRemark() + "");
            sheetRow.createCell(11).setCellValue((selectedList.get(i).getEnterpriseName() + "").equals("null") ? "" : selectedList.get(i).getEnterpriseName() + "");
            //公共字段
            sheetRow.createCell(12).setCellValue((selectedList.get(i).getCreateTime() + "").equals("null") ? "" : selectedList.get(i).getCreateTime() + "");
            sheetRow.createCell(13).setCellValue((selectedList.get(i).getCreateBy() + "").equals("null") ? "" : selectedList.get(i).getCreateBy() + "");
            sheetRow.createCell(14).setCellValue((selectedList.get(i).getCreateName() + "").equals("null") ? "" : selectedList.get(i).getCreateName() + "");
            sheetRow.createCell(15).setCellValue((selectedList.get(i).getUpdateTime() + "").equals("null") ? "" : selectedList.get(i).getUpdateTime() + "");
            sheetRow.createCell(16).setCellValue((selectedList.get(i).getUpdateBy() + "").equals("null") ? "" : selectedList.get(i).getUpdateBy() + "");
            sheetRow.createCell(17).setCellValue((selectedList.get(i).getUpdateName() + "").equals("null") ? "" : selectedList.get(i).getUpdateName() + "");
            sheetRow.createCell(18).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.err.println("\n数据导出完成!共导出 " + count + " 条数据。");
        return "数据导出完成!共导出 " + count + " 条数据。";
    }

    /**
     * 远程调用方法
     */
    public boolean shopDto(HtShopDTO shopDto) throws Exception {
        TbTradeArea tbTradeArea = tbTradeAreaService.updateHandler(shopDto.getFieldCode(), shopDto.getFieldName(), shopDto.getCustomsCode());
        TbShop tbShop = this.findByCode(shopDto.getShopNo());
        boolean newShop = false;
        if (tbShop == null) {
            newShop = true;
            tbShop = new TbShop();
            tbShop.setCreateTime(new Date());
        }
        BeanUtils.copyProperties(shopDto, tbShop, "id");
        //无则新增商铺
        tbShop.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode()); // 默认可用
        tbShop.setTradeAreaId(tbTradeArea.getId()).setTradeAreaName(tbTradeArea.getName());
        tbShop.setCreateName("航通").setCreateTime(new Date()); // 创建人 // 创建时间
        tbShop.setStatus(Status.STATUS_ONE.getCode()); // 可用状态
        if (newShop) {
        tbShop.insert();
        }


        TbEnterprise enterprise = tbEnterpriseService.findBydutyParagraph(shopDto.getShopSccd());
        boolean isNew = false;
        if (enterprise == null) {
            isNew = true;
            enterprise = new TbEnterprise();
        }
        BeanUtils.copyProperties(tbShop, enterprise, "id");
        //设置基本属性
        enterprise.setOwnerName(shopDto.getOwnerName()).setDutyParagraph(shopDto.getShopSccd()); // 个人姓名
        enterprise.setDeleteStatus(Long.valueOf(DeleteStatus.DELETE_STATUS_ON.getCode())); // 逻辑删除,默认未删除
        enterprise.setJudgeStatus(JudgeStatus.JUDGE_STATUS_ONE.getCode());  // 审核状态,默认审核通过
        enterprise.setJudgeTime(new Date()); // 审核时间
        enterprise.setShopId(tbShop.getId()); // 关联自己旗下的店铺  店铺ID
        enterprise.setShopName(shopDto.getShopName()); // 店铺ID
        enterprise.setBankAccount(shopDto.getBankAccount()); // 银行账户
        enterprise.setBank(shopDto.getBank()); // 银行名称
        enterprise.setAddress(tbShop.getAddress()); // 地址
        enterprise.setType(null);  //  商户分类(自营商铺=自营商铺,劳务商铺=劳务商铺)
        enterprise.setIsLock(IsLock.IS_LOCK_ON.getCode()); // 默认未被锁定
        enterprise.setTradeAreaId(tbTradeArea.getId()).setBank(shopDto.getBank()).setBankAccount(shopDto.getBankAccount())
                .setNationality(shopDto.getShopType().equals("1") ? "中方商铺" : "外国商铺")
                .setLegalPerson(shopDto.getAgentName()).setIdCard(shopDto.getAgentCiphertextIdno())
                .setTradeAreaName(tbTradeArea.getName());
        boolean result=isNew?tbEnterpriseService.save(enterprise):tbEnterpriseService.updateById(enterprise);
        tbShop.setEnterpriseId(enterprise.getId()).setEnterpriseName(enterprise.getOwnerName());
        StaticLog.info("shop:{}", JSONUtil.toJsonStr(tbShop));
        tbShop.updateById();
        //新增外籍商户
        if (isNew) {
            //远程调用生成商家账户方法
            AppUserCreateDTO createDTO = new AppUserCreateDTO();
            createDTO.setAuth("1");
            createDTO.setUserType(UserType.USER_TYPE_ENTERPRISE.getCode() + "");
            createDTO.setPhone(enterprise.getOwnerTel());
            createDTO.setName(enterprise.getOwnerName());
            createDTO.setFkId(enterprise.getId());
            FeignFactory.adminInterface.createAccount(createDTO);
            return true;
        }
        return true;
    }

    /**
     * 根据编号查询
     *
     * @param shopNo
     * @return
     */
    public TbShop findByCode(String shopNo) {
        QueryWrapper<TbShop> ew = new QueryWrapper<>();
        ew.lambda().eq(TbShop::getShopNo, shopNo);
        List<TbShop> list = list(ew);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 远程调用: 根据电话查询商铺
     */
    public List<ShopDto> getShopDtoListByPhone(String phone) {
        List<TbShop> tbShopList = tbShopMapper.selectList(new LambdaQueryWrapper<TbShop>()
                        .eq(TbShop::getOwnerTel, phone)
//				.eq(TbShop::getStatus, Status.STATUS_ONE.getCode())
//				.eq(TbShop::getDeleteStatus,DeleteStatus.DELETE_STATUS_ON.getCode())
//				.eq(TbShop::getEDStatus, HtDeleteStatus.DELETE_STATUS_ONE.getCode())
        );
        List<ShopDto> result = new ArrayList<>();
        if (tbShopList.size() > 0) {
            tbShopList.forEach(item -> {
                ShopDto shopDto = new ShopDto();
                BeanUtils.copyProperties(item, shopDto);
                result.add(shopDto);
            });
        }
        return result;
    }

    /**
     * 根据铺主姓名查询商铺是否存在
     */
    public boolean getByName(String name) {
        LambdaQueryWrapper<TbShop> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbShop::getOwnerName, name);

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

    /**
     * 商家备案验证查询-银行回复新开户或变更数据
     */
    public boolean updateBySXB009(BankInfoDto bankInfoDto) {
        LambdaUpdateWrapper<TbShop> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TbShop::getOwnerIdtype, bankInfoDto.getPapersType());
        wrapper.set(TbShop::getShopSccd, bankInfoDto.getPapersNo());
        wrapper.set(TbShop::getOwnerTel, bankInfoDto.getTel());
        wrapper.set(TbShop::getBankAccount, bankInfoDto.getAccount());
        wrapper.set(TbShop::getBank, bankInfoDto.getPayBankCode());
        wrapper.set(TbShop::getNationality, bankInfoDto.getNationality());
        //wrapper.set(TbShop::getAbroad, bankInfoDto.getAbroad());

        wrapper.eq(TbShop::getOwnerName, bankInfoDto.getName());

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