package com.rongwei.bscommon.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.CommonDao;
import com.rongwei.bscommon.sys.dao.EquWarrantyProviderMapperDao;
import com.rongwei.bscommon.sys.service.EquWarrantyProviderService;
import com.rongwei.bscommon.sys.utils.ExcelUtils;
import com.rongwei.bscommon.sys.utils.ExceptionUtils;
import com.rongwei.bscommon.sys.utils.StringUtil;
import com.rongwei.bsentity.domain.EquWarrantyProviderDo;
import com.rongwei.rwadmincommon.system.domain.*;
import com.rongwei.rwadmincommon.system.service.SysDictService;
import com.rongwei.rwadmincommon.system.vo.SysOrganizationVo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备子系统——保修商 服务实现类
 * </p>
 *
 * @author fpy
 * @since 2023-12-01
 */
@Service
public class EquWarrantyProviderServiceImpl extends ServiceImpl<EquWarrantyProviderMapperDao, EquWarrantyProviderDo> implements EquWarrantyProviderService {

    @Autowired
    private EquWarrantyProviderService equWarrantyProviderService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private CommonDao commonDao;

    @Override
    public R importEquWarrantyProvider(MultipartFile file) {
        List<SysDictDo> ynByType = sysDictService.getDictsByType("srm_yn");
        try {
            // 查询所有工厂数据
            List<SysOrganizationVo> factoryList = commonDao.getAllFactoryNameAndId();
            StringBuilder allStrBuilder = new StringBuilder();
            Sheet sheet = new XSSFWorkbook(file.getInputStream()).getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            List<EquWarrantyProviderDo> equWarrantyProviderDos = new ArrayList<>();
            List<String> factorys = new ArrayList<>();
            List<String> zusccs = new ArrayList<>();
            List<String> names = new ArrayList<>();
            String factoryId = "";
            String deptId = "";
            for (int i = 1; i <= lastRowNum; i++) {
                StringBuilder stringBuilder = new StringBuilder();
                EquWarrantyProviderDo equWarrantyProviderDo = new EquWarrantyProviderDo();
                Row row = sheet.getRow(i);
                if (ExcelUtils.isRowEmpty(row)){
                    continue;
                }
                String code = row.getCell(0) == null ? "" : row.getCell(0).toString().trim();
                String name = row.getCell(1) == null ? "" : row.getCell(1).toString().trim();
                String zuscc = row.getCell(2) == null ? "" : row.getCell(2).toString().trim();
                String legal = row.getCell(3) == null ? "" : row.getCell(3).toString().trim();
                String isPrivately = row.getCell(4) == null ? "" : row.getCell(4).toString().trim();
                String mainContacts = row.getCell(5) == null ? "" : row.getCell(5).toString().trim();
                String phone = row.getCell(6) == null ? "" : row.getCell(6).toString().trim();
                String factory = row.getCell(7) == null ? "" : row.getCell(7).toString().trim();
                String dept = row.getCell(8) == null ? "" : row.getCell(8).toString().trim();
                if (StringUtils.isBlank(code)){
                    stringBuilder.append("保修商编号必填");
                }
                if (StringUtils.isBlank(name)){
                    stringBuilder.append("保修商名称必填");
                }
                if (StringUtils.isBlank(zuscc)){
                    stringBuilder.append("统一社会信用代码必填");
                }
                boolean containFactory = factorys.contains(factory);
                boolean containName = names.contains(name);
                boolean containZuscc = zusccs.contains(zuscc);
                if (StringUtil.isNotBlank(factory)){
                    factorys.add(factory);
                }
                if (StringUtil.isNotBlank(name)){
                    names.add(name);
                }
                if (StringUtil.isNotBlank(zuscc)){
                    zusccs.add(zuscc);
                }
                if (containFactory){
                    if (containName){
                        stringBuilder.append("表格中当前工厂下已存在该名称，不可重复录入");
                    }
                    if (containZuscc){
                        stringBuilder.append("表格中当前工厂下已存在该统一社会信用代码，不可重复录入");
                    }
                }
                if (StringUtils.isNotBlank(factory)){
                    List<SysOrganizationVo> resultList = factoryList.stream().filter(p -> p.getFullname().equals(factory)).collect(Collectors.toList());
                    if (resultList.size()>0){
                        factoryId = resultList.get(0).getId();
                        //当前用户所属工厂、【保修商名称】作唯一校验
                        if (StringUtils.isNotBlank(name)){
                            QueryWrapper<EquWarrantyProviderDo> entity = new QueryWrapper<EquWarrantyProviderDo>().eq("DELETED", 0).eq("WARRANTYPROVIDER",name).eq("TENANTID",factoryId).last("limit 1");
                            EquWarrantyProviderDo providerNameDo = equWarrantyProviderService.getOne(entity);
                            if (providerNameDo!= null){
                                stringBuilder.append(String.format("在%s中%s已存在，不可重复导入",factory,name));
                            }
                        }
                        //当前用户所属工厂、【统一社会信用代码】作唯一校验
                        if (StringUtils.isNotBlank(zuscc)){
                            if (StringUtil.isScience(zuscc)){
                                BigDecimal formatAccount = new BigDecimal(zuscc);
                                zuscc = formatAccount.setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString();
                            }
                            QueryWrapper<EquWarrantyProviderDo> entity = new QueryWrapper<EquWarrantyProviderDo>().eq("DELETED", 0).eq("ZUSCC",zuscc).eq("TENANTID",factoryId).last("limit 1");
                            EquWarrantyProviderDo providerZusccDo = equWarrantyProviderService.getOne(entity);
                            if (providerZusccDo!= null){
                                stringBuilder.append(String.format("在%s中%s保修商已存在，不可重复导入",factory,zuscc));
                            }
                        }
                    }else {
                        stringBuilder.append("所属工厂填写有误");
                    }
                }else {
                    stringBuilder.append("所属工厂必填");
                }
                if (StringUtil.isNotBlank(stringBuilder)) {
                    allStrBuilder.append("第").append(i + 1).append("行").append(stringBuilder).append("<br>");
                }else {
                    //处理数据
                    if (StringUtil.isScience(code)){
                        BigDecimal formatAccount = new BigDecimal(code);
                        code = formatAccount.setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString();
                    }else {
                        code = StringUtil.formatDecimal(code);
                    }
                    if (StringUtils.isNotBlank(phone)){
                        if (StringUtil.isScience(phone)){
                            BigDecimal formatPhone = new BigDecimal(phone);
                            phone = formatPhone.setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString();
                        }
                    }
                    if (org.apache.commons.lang.StringUtils.isNotBlank(isPrivately)) {
                        String isPrivatelyDictName = isPrivately;
                        isPrivately = ynByType.stream().filter(dictDo -> isPrivatelyDictName.contains(dictDo.getName()))
                                .map(SysDictDo::getValue).collect(Collectors.joining(","));
                    }
                    if (StringUtils.isNotBlank(dept)){
                        deptId = commonDao.getIdByFactoryIdAndDept(factoryId,dept);
                    }
                    equWarrantyProviderDo.setId(SecurityUtil.getUUID())
                            .setWarrantyprovidercode(code)
                            .setWarrantyprovider(name)
                            .setZuscc(zuscc)
                            .setLegalperson(legal)
                            .setIsprivatelyoperated(isPrivately)
                            .setPrimarycontact(mainContacts)
                            .setContactphone(phone)
                            .setTenantid(factoryId)
                            .setBelongfactory(factory)
                            .setManagedepartmentid(deptId)
                            .setManagedepartment(dept)
                            .setEnablestate("10")
                            .setClassify("10");
                    equWarrantyProviderDos.add(equWarrantyProviderDo);
                }
            }
            String errMsg = allStrBuilder.toString();
            if (StringUtils.isNotBlank(errMsg)){
                return R.error(errMsg);
            }else {
                if (equWarrantyProviderDos.size()>0){
                    equWarrantyProviderService.saveOrUpdateBatch(equWarrantyProviderDos);
                }
            }
        } catch (IOException e) {
            ExceptionUtils.printExceptionDetail(e,"保修商导入异常");
        }
        return R.ok();
    }
}
