package com.ruoyi.basicData.service.impl;


import com.ruoyi.basicData.domain.FleetCompanyMsg;
import com.ruoyi.basicData.domain.TCorps;
import com.ruoyi.basicData.mapper.FleetCompanyMsgMapper;
import com.ruoyi.basicData.mapper.TCorpsMapper;
import com.ruoyi.basicData.service.IFleetCompanyMsgService;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.orderPlan.domain.Ftmsorderbillsplans;
import com.ruoyi.orderPlan.mapper.FtmsorderbillsplansMapper;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static com.ruoyi.common.utils.poi.Excel.filter;

/**
 * 【车队】Service业务层处理
 *
 * @author ruoyi
 * @date 2021-03-04
 */
@Slf4j
@Service
public class FleetCompanyMsgServiceImpl implements IFleetCompanyMsgService {
    @Autowired
    private TCorpsMapper tCorpsMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private FleetCompanyMsgMapper fleetCompanyMsgMapper;

    @Autowired
    private FtmsorderbillsplansMapper ftmsorderbillsplansMapper;

    /**
     * 查询【车队】
     *
     * @param id 【车队】ID
     * @return 【车队】
     */
    @Override
    public TCorps selectFleetCompanyMsgById(Long id) {
        return tCorpsMapper.selectTCorpsById(id);
    }

    /**
     * 查询【车队】列表
     *
     * @param fleetCompanyMsg 【车队】
     * @return 【车队】
     */
    @Override
    public List<FleetCompanyMsg> selectFleetCompanyMsgList(FleetCompanyMsg fleetCompanyMsg) {
        return fleetCompanyMsgMapper.selectFleetCompanyMsgList(fleetCompanyMsg);
    }

    @Override
    public List<Map<String, Object>> selectFleetCompanyMsgListMap(FleetCompanyMsg fleetCompanyMsg) {
        return fleetCompanyMsgMapper.selectFleetCompanyMsgListMap(fleetCompanyMsg);
    }

    /**
     * 新增【车队】
     *
     * @param tCorps 【车队】
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertFleetCompanyMsg(TCorps tCorps) {
        String typeValue = "[\"100\"]";
        tCorps.setfTypeid(typeValue);
        tCorps.setfTypename("车队");
        tCorps.setfStatus("0");
        SysDept dept = sysDeptMapper.selectDeptByDeptName("外部用户");
        if (StringUtils.isNull(dept)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("未找到部门信息，请添加后再提交");
        }
        if (StringUtils.isNotNull(tCorps.getfId())) {
            tCorps.setUpdateTime(new Date());
            tCorps.setUpdateBy(SecurityUtils.getUsername());
            tCorpsMapper.updateTCorps(tCorps);
            // 更新用户信息
            SysUser sysUser = sysUserMapper.selectUserByUserName(tCorps.getLoginAccount());
            if (StringUtils.isNull(sysUser)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("未找到用户信息，请添加后再提交");
            }
            sysUser.setUserType("22");
            sysUser.setUserSystem("2");
            sysUser.setUpdateTime(new Date());
            sysUser.setDeptId(dept.getDeptId());
            sysUser.setPhonenumber(tCorps.getfTel());
            sysUser.setUpdateBy(SecurityUtils.getUsername());
            sysUser.setPassword(SecurityUtils.encryptPassword(tCorps.getfTel()));
            sysUserMapper.updateUser(sysUser);
            return AjaxResult.success();
        } else {
            tCorps.setCreateTime(new Date());
            tCorps.setCreateBy(SecurityUtils.getUsername());
            tCorpsMapper.insertTCorps(tCorps);
            AjaxResult ajaxResult = createUser(tCorps, dept);
            String code = ajaxResult.get("code").toString();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ajaxResult;
            }
            return AjaxResult.success();
        }
    }

    @Transactional
    public AjaxResult createUser(TCorps tCorps, SysDept dept) {
        // 创建用户
        SysUser user = new SysUser();
        user.setUserType("22");
        user.setUserSystem("2");
        user.setCreateTime(new Date());
        user.setDeptId(dept.getDeptId());
        user.setNickName(tCorps.getfTel());
        user.setPhonenumber(tCorps.getfTel());
        user.setUserName(tCorps.getLoginAccount());
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(tCorps.getfTel()));
        sysUserMapper.insertUser(user);
        // 查询是否存在车队 角色
        SysRole role = sysRoleMapper.selectRoleByName("车队");
        if (StringUtils.isNull(role)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("未找到外部用户角色，请添加角色后再提交");
        }
        // 创建用户与角色关联
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(role.getRoleId());
        sysUserRole.setUserId(user.getUserId());
        list.add(sysUserRole);
        sysUserRoleMapper.batchUserRole(list);
        return AjaxResult.success();
    }

    /**
     * 修改【车队】
     *
     * @param fleetCompanyMsg 【车队】
     * @return 结果
     */
    @Override
    public int updateFleetCompanyMsg(FleetCompanyMsg fleetCompanyMsg) {
        fleetCompanyMsg.setUpdateTime(new Date());
        return fleetCompanyMsgMapper.updateFleetCompanyMsg(fleetCompanyMsg);
    }

    /**
     * 批量删除【车队】
     *
     * @param ids 需要删除的【车队】ID
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteFleetCompanyMsgByIds(Long[] ids) {
        int i = 1;
        for(Long id:ids){
            TCorps corps = tCorpsMapper.selectTCorpsById(id);
            Ftmsorderbillsplans ftmsorderbillsplans =new Ftmsorderbillsplans();
            ftmsorderbillsplans.setCarcorPid(id);
            if(ftmsorderbillsplansMapper.selectftmsorderbillsplansCountList(ftmsorderbillsplans) > 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("客户第" + i + "行调度安排已被使用不可删除");
            }
            tCorpsMapper.deleteTCorpsById(id);
            SysUser sysUser = sysUserMapper.selectUserByUserName(corps.getLoginAccount());
            sysUserMapper.deleteUserById(sysUser.getUserId());
            sysUserRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
            i++;
        }
        return AjaxResult.success();
    }

    /**
     * 删除【车队】信息
     *
     * @param id 【车队】ID
     * @return 结果
     */
    @Override
    public int deleteFleetCompanyMsgById(Long id) {
        TCorps corps = tCorpsMapper.selectTCorpsById(id);
        SysUser sysUser = sysUserMapper.selectUserByUserName(corps.getfTel());
        sysUserMapper.deleteUserById(sysUser.getUserId());
        sysUserRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
        return tCorpsMapper.deleteTCorpsById(id);
    }

    @Override
    public String checkUFNoUnique(FleetCompanyMsg fleetCompanyMsg) {
        FleetCompanyMsg fleetCompanyMsg1 = fleetCompanyMsgMapper.checkFNoUnique(fleetCompanyMsg.getCompanyName());
        if (StringUtils.isNotNull(fleetCompanyMsg1) && fleetCompanyMsg1.getId() != fleetCompanyMsg.getId()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 下拉框查询【车队】id、name列表
     *
     * @param fleetCompanyMsg 条件
     * @return 结果
     */
    @Override
    public List<FleetCompanyMsg> selectFleetCompanyMsgIdNameList(FleetCompanyMsg fleetCompanyMsg) {
        return fleetCompanyMsgMapper.selectFleetCompanyMsgIdNameList(fleetCompanyMsg);
    }

    @Override
    public AjaxResult importCreateCompanyMsg(MultipartFile file) {
        List<FleetCompanyMsg> fleetCompanyMsgs = new ArrayList<>();

        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            int line = 0;
            for (Row rows : sheet) {
                line++;
                if (rows.getRowNum() == 0) {
                    continue;
                }
                FleetCompanyMsg companyMsg = new FleetCompanyMsg();
                for (int a = 0; a < rows.getPhysicalNumberOfCells(); a++) {
                    Cell cell = rows.getCell(a);
                    String value = filter(sheet.getRow(0), CellReference.convertNumToColString(cell.getColumnIndex()));
                    switch (value) {
                        case "*公司名称":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel车队数据第" + line + "行数据缺少公司名称");
                            }
                            companyMsg.setCompanyName(cell.getStringCellValue());
                            break;
                        case "*公司地址":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel车队数据第" + line + "行数据缺少公司地址");
                            }
                            companyMsg.setCompanyAddress(cell.getStringCellValue());
                            break;
                        case "*公司开户账行":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel车队数据第" + line + "行数据缺少公司开户账行");
                            }
                            companyMsg.setOpeningBank(cell.getStringCellValue());
                            break;
                        case "*银行账号":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel车队数据第" + line + "行数据缺少银行账号");
                            }
                            companyMsg.setBankAccount(cell.getStringCellValue());
                            break;
                        case "登录账号":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel车队数据第" + line + "行数据缺少登录账号");
                            }
                            companyMsg.setLoginAccount(cell.getStringCellValue());
                            break;
                        case "信用等级":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setCreditLv(cell.getStringCellValue());
                            break;
                        case "账期天数":
                            //设置单元格类型
                            cell.setCellType(CellType.NUMERIC);
                            companyMsg.setPaymentDays(new Double(cell.getNumericCellValue()).longValue());
                            break;
                        case "联系人":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setLinkMan(cell.getStringCellValue());
                            break;
                        case "电话":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setLinkPhone(cell.getStringCellValue());
                            break;
                        case "传真":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setFax(cell.getStringCellValue());
                            break;
                        case "email":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setEmail(cell.getStringCellValue());
                            break;
                        case "总公司":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setHeadOffice(cell.getStringCellValue());
                            break;
                        case "注册资本":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setRegisterdCapital(cell.getStringCellValue());
                            break;
                        case "法人":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setLegalPerson(cell.getStringCellValue());
                            break;
                        case "所属行业":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setInsdustry(cell.getStringCellValue());
                            break;
                        case "社会统一信用代码":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setCreditNum(cell.getStringCellValue());
                            break;
                        case "登记机关":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setRegisterOrganization(cell.getStringCellValue());
                            break;
                        case "成立日期":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            Double d = Double.parseDouble(String.valueOf(cell.getNumericCellValue()));
                            companyMsg.setDateOfEstablishment(HSSFDateUtil.getJavaDate(d));
                            break;
                        case "企业类型":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setCompanyType(cell.getStringCellValue());
                            break;
                        case "营业期限":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            Double businessDead = Double.parseDouble(String.valueOf(cell.getNumericCellValue()));
                            companyMsg.setBusinessDeadline(HSSFDateUtil.getJavaDate(businessDead));
                            break;
                        case "营业区域":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setBusinessArea(cell.getStringCellValue());
                            break;
                        case "审核年检日期":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            Double aDouble = Double.parseDouble(String.valueOf(cell.getNumericCellValue()));
                            companyMsg.setAnnualDate(HSSFDateUtil.getJavaDate(aDouble));
                            break;
                        case "注册地址":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setRegisterdAddress(cell.getStringCellValue());
                            break;
                        case "经营范围":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            companyMsg.setManageScope(cell.getStringCellValue());
                            break;
                    }
                }
                fleetCompanyMsgs.add(companyMsg);
            }
        } catch (IOException e) {
            log.info("导入Excel异常：" + e);
            e.printStackTrace();
        }
        System.out.println(fleetCompanyMsgs);
        return null;
    }
}
