package com.pj.tb_purchaser;

import com.pj.enummj.DeleteStatus;
import com.pj.enummj.IsLock;
import com.pj.enummj.JudgeStatus;
import com.pj.tb_purchaser.param.PurchaserParam;
import com.pj.tb_purchaser.vo.PurchaserParamVo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author Mechrevo
 * @Date 2023 07 21 21 13
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class MethodPurchaserService {
    
    @Autowired
    private TbPurchaserService tbPurchaserService;


    public TbPurchaser setPurchaserProperties(PurchaserParam purchaser) throws ParseException {
        //开始保存收购商信息
        //注册/认证时间
        TbPurchaser tbPurchaser = new TbPurchaser();
        //设置名称
        tbPurchaser.setName(purchaser.getName());
        //审核状态
        tbPurchaser.setJudgeStatus(JudgeStatus.JUDGE_STATUS_ZERO.getCode()); // 待审核
        //默认未被锁
        tbPurchaser.setIsLock(IsLock.IS_LOCK_ON.getCode());
        //注册时间
        tbPurchaser.setRegisterTime(new Date());
        //创建时间
        tbPurchaser.setCreateTime(new Date());
        //创建人
        tbPurchaser.setCreateBy(String.valueOf(purchaser.getLoginUserId()));
        //删除状态:启用
        tbPurchaser.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());
        //地址
        tbPurchaser.setAddress(purchaser.getAddress());
        //计算年龄
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        // 提取身份证号中的出生日期
        String idNumber = purchaser.getCorporateIdCard();
        String birthDateStr = idNumber.substring(6, 14);
        // 将出生日期字符串转换为Date类型
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date birthDate = dateFormat.parse(birthDateStr);
        // 计算年龄
        calendar.setTime(birthDate);
        int birthYear = calendar.get(Calendar.YEAR);
        int age = currentYear - birthYear;
        tbPurchaser.setAge(age);
        //法人
        tbPurchaser.setLegalPerson(purchaser.getCorporateName());
        //身份证
        tbPurchaser.setIdCard(purchaser.getCorporateIdCard());
        //手机号
        tbPurchaser.setContact(purchaser.getLinkPhone());
        //营业执照
        tbPurchaser.setBusinessLicense(purchaser.getBusinessLicense());
        //银行编号
        tbPurchaser.setBankNo(purchaser.getBankNo());
        //银行账户
        tbPurchaser.setBankAccount(purchaser.getBankAccount());
        //银行名称
        tbPurchaser.setBankName(purchaser.getBankName());
        //审核状态,默认待审核
        tbPurchaser.setJudgeStatus(JudgeStatus.JUDGE_STATUS_ZERO.getCode());
        tbPurchaser.setDutyParagraph(purchaser.getDutyParagraph());
        return tbPurchaser;
    }

    /**
     * 认证时封装收购商信息
     * @param tbPurchaser
     * @return
     */
    public PurchaserParamVo setPurchaserParamProperties(TbPurchaser tbPurchaser){
        PurchaserParamVo purchaserParam = new PurchaserParamVo();
        BeanUtils.copyProperties(tbPurchaser,purchaserParam);
        purchaserParam.setLoginUserId(Long.valueOf(tbPurchaser.getCreateBy()));
        purchaserParam.setDutyParagraph(tbPurchaser.getDutyParagraph());
        purchaserParam.setCorporateName(tbPurchaser.getLegalPerson());
        purchaserParam.setCorporateIdCard(tbPurchaser.getIdCard());
        purchaserParam.setLinkPhone(tbPurchaser.getContact());
        return purchaserParam;
    }

    /**
     * 方法抽取  导入
     * @param row
     * @param sheet
     * @param count
     * @return
     */
    public int importMethod(HSSFRow row, HSSFSheet sheet, int count){

        //创建接收集合
        List<TbPurchaser> list = new ArrayList<>();

        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            //封装数据到行对象
            row = sheet.getRow(i);
            //定义返回值实体
            TbPurchaser tbPurchaser = new TbPurchaser();
            //解析数据
            if(row.getCell(1) != null)
                tbPurchaser.setName(row.getCell(1).getStringCellValue());

            if(row.getCell(2) != null)
                tbPurchaser.setLegalPerson(row.getCell(2).getStringCellValue());

            if(row.getCell(3) != null)
                tbPurchaser.setIdCard(row.getCell(3).getStringCellValue());

            if(row.getCell(4) != null)
                tbPurchaser.setContact(row.getCell(4).getStringCellValue());

            if(row.getCell(5) != null)
                tbPurchaser.setBusinessLicense(row.getCell(5).getStringCellValue());

            if(row.getCell(6) != null)
                tbPurchaser.setBankNo(row.getCell(6).getStringCellValue());

            if(row.getCell(7) != null)
                tbPurchaser.setBankName(row.getCell(7).getStringCellValue());

            if(row.getCell(8) != null)
                tbPurchaser.setBankAccount(row.getCell(8).getStringCellValue());

            if(row.getCell(9) != null)
                tbPurchaser.setDutyParagraph(row.getCell(9).getStringCellValue());

            if(row.getCell(10) != null)
                tbPurchaser.setAddressIds(row.getCell(10).getStringCellValue());

            if(row.getCell(11) != null)
                tbPurchaser.setAddress(row.getCell(11).getStringCellValue());

            if(row.getCell(12) != null)
                tbPurchaser.setIdCard(row.getCell(12).getStringCellValue());

            HSSFCell cell21 = row.getCell(13);
            if (cell21 != null && (cell21.getCellType() == CellType.NUMERIC || cell21.getCellType() == CellType.FORMULA))
                tbPurchaser.setJudgeStatus((int) cell21.getNumericCellValue());

            if(row.getCell(14) != null)
                tbPurchaser.setJudgeContent(row.getCell(14).getStringCellValue());

            HSSFCell cell2 = row.getCell(15);
            if (cell2 != null && cell2.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell2)) {
                tbPurchaser.setJudgeTime(cell2.getDateCellValue());
            }

            HSSFCell cell16 = row.getCell(16);
            if (cell16 != null && cell16.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell16)) {
                tbPurchaser.setRegisterTime(cell16.getDateCellValue());
            }

            if(row.getCell(17) != null)
                tbPurchaser.setPersonId(row.getCell(17).getStringCellValue());

            //公共字段
            HSSFCell cell18 = row.getCell(18);
            if (cell18 != null && cell18.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell18)) {
                tbPurchaser.setCreateTime(cell18.getDateCellValue());
            }

            if(row.getCell(19) != null && !row.getCell(19).toString().trim().equals(""))
                tbPurchaser.setCreateBy(row.getCell(19).getStringCellValue());

            if(row.getCell(20) != null && !row.getCell(20).toString().trim().equals(""))
                tbPurchaser.setCreateName(row.getCell(20).getStringCellValue());

            if(row.getCell(21) != null && !row.getCell(21).toString().trim().equals(""))
                tbPurchaser.setUpdateBy(row.getCell(21).getStringCellValue());

            if(row.getCell(22) != null && !row.getCell(22).toString().trim().equals(""))
                tbPurchaser.setUpdateName(row.getCell(22).getStringCellValue());

            HSSFCell cell3 = row.getCell(23);
            if (cell3 != null && cell3.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell3)) {
                tbPurchaser.setUpdateTime(cell3.getDateCellValue());
            }
            //删除状态,默认可用
            tbPurchaser.setDeleteStatus(1);
			//添加到集合
			list.add(tbPurchaser);

        }

        System.out.println("待处理数据量为: " + list.size() + " 条。");

        //创建多线程
        ExecutorService executorService = Executors.newFixedThreadPool(6);

        //每次100条
        int bai = 100;
        //计算需要创建的线程数
        int threads = (int) Math.ceil((double) list.size() / bai);
        for (int i = 0; i < threads; i++) {
            int start = i * bai;
            int end = Math.min(start + bai,list.size());

            //截取集合数量
            List<TbPurchaser> enterpriseList = list.subList(start, end);

            //多线程执行任务
            executorService.submit(() -> {
                tbPurchaserService.saveBatch(enterpriseList);
            });
            //计数
            count += enterpriseList.size();

        }
        //关闭线程池
        executorService.shutdown();

        return count;
    }
}
