package com.ruoyi.basicData.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.basicData.domain.TCorps;
import com.ruoyi.basicData.domain.TCustomerContact;
import com.ruoyi.basicData.mapper.TCorpsMapper;
import com.ruoyi.basicData.mapper.TCustomerContactMapper;
import com.ruoyi.basicData.service.ITCorpsService;
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.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
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.warehouseBusiness.domain.TEnclosure;
import com.ruoyi.warehouseBusiness.domain.TWarehouseBills;
import com.ruoyi.warehouseBusiness.mapper.TEnclosureMapper;
import com.ruoyi.warehouseBusiness.mapper.TWarehouseBillsMapper;
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 java.util.*;

/**
 * 客户详情Service业务层处理
 *
 * @author ruoyi
 * @date 2020-12-11
 */
@Service
public class TCorpsServiceImpl implements ITCorpsService {
    @Autowired
    private TCorpsMapper tCorpsMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private TEnclosureMapper tEnclosureMapper;

    @Autowired
    private TCustomerContactMapper tCustomerContactMapper;

    @Autowired
    private TWarehouseBillsMapper tWarehouseBillsMapper;

    /**
     * 查询客户详情
     *
     * @param fId 客户详情ID
     * @return 客户详情
     */
    @Override
    @Transactional
    public Map<String, Object> selectTCorpsById(Long fId) {
        Map<String, Object> map = new HashMap<>();
        TCorps tCorps = tCorpsMapper.selectTCorpsById(fId);
        if (StringUtils.isNull(tCorps)) {
            return AjaxResult.error("未找到信息");
        }
        map.put("corp", tCorps);
       // List<TCustomerContact> customerContactList = tCustomerContactMapper.selectList(new EntityWrapper<TCustomerContact>().eq("f_pid", fId));
        TCustomerContact tCustomerContact = new TCustomerContact();
        tCustomerContact.setfPid(fId);
        map.put("customerContact", tCustomerContactMapper.selectTCustomerContactList(tCustomerContact));
        map.put("attach", tEnclosureMapper.selectTEnclosureByPId(fId));
        return map;
    }

    /**
     * 查询客户详情列表
     *
     * @param tCorps 客户详情
     * @return 客户详情
     */
    @Override
    public List<TCorps> selectTCorpsList(TCorps tCorps) {
        if (StringUtils.isNotEmpty(tCorps.getfTypeid())) {
            tCorps.setfTypeid("\""+tCorps.getfTypeid()+"\"");
        }
        return tCorpsMapper.selectTCorpsList(tCorps);
    }

    /**
     *  车队使用，查询客户、司机信息、车队信息
     * @param fId
     * @return
     */
    @Override
    public List<TCorps> selectCorpList(Long fId) {
        return tCorpsMapper.selectCorpList(fId);
    }

    /**
     *  车队使用，查询客户、车队信息
     * @param tCorps
     * @return
     */
    @Override
    public List<TCorps> selectCustomerDriverList(TCorps tCorps) {
        return tCorpsMapper.selectCustomerDriverList(tCorps);
    }

    /**
     * 新增客户详情
     *
     * @param tCorps            客户详情
     * @param tCustomerContacts 客户联系人
     * @param loginUser         当前登陆人
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertTCorps(String tCorps, String tCustomerContacts, String attach, LoginUser loginUser) {
        if (StringUtils.isEmpty(tCorps)) {
            return AjaxResult.error("提交失败：客户信息为空");
        }
        Long fPid = null;
        SysUser user = loginUser.getUser();
        TCorps corps = JSONArray.parseObject(tCorps, TCorps.class);
        if (StringUtils.isNull(corps.getfId())) {
            corps.setCreateBy(user.getUserName());
            corps.setCreateTime(new Date());
            corps.setfStatus("0");
            tCorpsMapper.insertTCorps(corps);
            fPid=corps.getfId();
        } else {
            fPid=corps.getfId();
            corps.setUpdateBy(user.getUserName());
            corps.setUpdateTime(new Date());
            if(corps.getfStatus().equals("1")){
                TWarehouseBills tWarehouseBill =new TWarehouseBills();
                tWarehouseBill.setfCorpid(corps.getfId());
                List<TWarehouseBills>   tWarehouseBillList=tWarehouseBillsMapper.selectTWarehousebillsList(tWarehouseBill);
                if(tWarehouseBillList!=null && !tWarehouseBillList.isEmpty()){
                    return AjaxResult.error("客户在库存总账有记录不可变更状态");
                }
            }
            tCorpsMapper.updateTCorps(corps);
            tEnclosureMapper.deleteByFPid(fPid);
        }
        TCustomerContact tCustomerContact = new TCustomerContact();
        tCustomerContact.setfPid(corps.getfId());
        List<TCustomerContact> contactList = tCustomerContactMapper.selectTCustomerContactList(tCustomerContact);
        tCustomerContactMapper.deleteCustomerContactByCorps(fPid);
        if (StringUtils.isNotEmpty(tCustomerContacts) && !"[]".equals(tCustomerContacts)) {
            int line = 0;
            SysDept dept = sysDeptMapper.selectDeptByDeptName("外部用户");
            if (StringUtils.isNull(dept)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("未找到部门信息，请添加后再提交");
            }
            JSONArray jsonArray = JSONArray.parseArray(tCustomerContacts);
            List<TCustomerContact> customerContactList = JSONObject.parseArray(jsonArray.toJSONString(), TCustomerContact.class);
            for (TCustomerContact cc : customerContactList) {
                line++;
                if (StringUtils.isEmpty(cc.getfName())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("联系人第" + line + "行，缺少客户名称");
                }
                if (StringUtils.isEmpty(cc.getfTel())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("联系人第" + line + "行，缺少客户手机号");
                }
                if (StringUtils.isEmpty(cc.getfStatus())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("联系人第" + line + "行，缺少客户状态");
                }
                if (tCustomerContactMapper.checkTelUnique(cc.getfTel()) > 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("联系人第" + line + "行，手机号已存在");
                }
                if (StringUtils.isNull(cc.gettId())) {
                    if (sysUserMapper.selectUserByUserNameOrTel(cc.getfTel()) > 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("联系人第" + line + "行，手机号已被使用");
                    }
                    // 创建客户 登录账户
                    SysUser sysUser = new SysUser();
                    sysUser.setUserType("33");
                    sysUser.setUserSystem("2");
                    sysUser.setCreateTime(new Date());
                    sysUser.setUserName(cc.getfTel());
                    sysUser.setStatus(cc.getfStatus());
                    sysUser.setNickName(cc.getfName());
                    sysUser.setDeptId(dept.getDeptId());
                    sysUser.setPhonenumber(cc.getfTel());
                    sysUser.setCreateBy(user.getUserName());
                    sysUser.setPassword(SecurityUtils.encryptPassword(cc.getfTel()));
                    sysUserMapper.insertUser(sysUser);
                    // 新增用户与角色管理
                    // 查询是否存在车队 角色
                    SysRole role = roleMapper.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(sysUser.getUserId());
                    list.add(sysUserRole);
                    userRoleMapper.batchUserRole(list);
                    cc.setUserId(sysUser.getUserId());
                } else {
                    TCustomerContact contact = new TCustomerContact();
                    for (TCustomerContact c : contactList) {
                        if (c.gettId().equals(cc.gettId())) {
                            if (StringUtils.isNull(c.getUserId())) {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.error("该客户联系人异常，请刷新后提交");
                            }
                            contact.setUserId(c.getUserId());
                            break;
                        }
                    }
                    SysUser use = sysUserMapper.selectUserById(contact.getUserId());
                    if (StringUtils.isNull(use)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("该手机号未找到用户信息，请确认操作用户信息是否被删除");
                    }
                    use.setUpdateTime(new Date());
                    use.setNickName(cc.getfName());
                    use.setStatus(cc.getfStatus());
                    use.setDeptId(dept.getDeptId());
                    use.setPhonenumber(cc.getfTel());
                    use.setUpdateBy(user.getUserName());
                    sysUserMapper.updateUser(use);
                }
                cc.setfPid(fPid);
                cc.setfStatus("0");
                cc.setCreateTime(new Date());
                cc.setCreateBy(user.getUserName());
                tCustomerContactMapper.insertTCustomerContact(cc);
            }
        }
        if (StringUtils.isNotEmpty(attach) && !"[]".equals(attach)) {
            JSONArray jsonArray = JSONArray.parseArray(attach);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonArray.toJSONString(), TEnclosure.class);
            int line = 1;
            for (TEnclosure t : tEnclosureList) {
                if (StringUtils.isEmpty(t.getfUrl())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("附件表第" + line + "行数据未找到附件地址");
                }
                t.setfPid(fPid);
                t.setCreateTime(new Date());
                t.setCreateBy(loginUser.getUsername());
                tEnclosureMapper.insertTEnclosure(t);
                line++;
            }
        }
        return AjaxResult.success();
    }

    /**
     * 修改客户详情
     *
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult updateTCorps(TCorps tCorps) {
        TWarehouseBills tWarehouseBill =new TWarehouseBills();
        tWarehouseBill.setfCorpid(tCorps.getfId());
        List<TWarehouseBills>   tWarehouseBillList=tWarehouseBillsMapper.selectTWarehousebillsList(tWarehouseBill);
        if(tWarehouseBillList!=null && !tWarehouseBillList.isEmpty()){
            return AjaxResult.error("客户在库存总账有记录不可变更状态");
        }
        tCorps.setUpdateTime(DateUtils.getNowDate());
        tCorpsMapper.updateTCorps(tCorps);
        return AjaxResult.success();
    }

    /**
     * 批量删除客户详情
     *
     * @param fIds 需要删除的客户详情ID
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteTCorpsByIds(Long[] fIds) {
        //return tCorpsMapper.deleteTCorpsByIds(fIds);
        // 查询仓库主表 是否有客户存在
        int i = 1;
        for(Long id:fIds){
            TWarehouseBills tWarehouseBill =new TWarehouseBills();
            tWarehouseBill.setfCorpid(id);
            List<TWarehouseBills>   tWarehouseBillList=tWarehouseBillsMapper.selectTWarehousebillsList(tWarehouseBill);
            if(tWarehouseBillList!=null && !tWarehouseBillList.isEmpty()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("客户第" + i + "行仓库有货物不可删除");
            }
            tCorpsMapper.deleteTCorpsById(id);
            tEnclosureMapper.deleteByFPid(id);
            i++;
        }
        return AjaxResult.success();
    }

    /**
     * 删除客户详情信息
     *
     * @param fId 客户详情ID
     * @return 结果
     */
    @Override
    public int deleteTCorpsById(Long fId) {
        return tCorpsMapper.deleteTCorpsById(fId);
    }

    @Override
    public String checkUFNoUnique(TCorps tCorps) {
        TCorps tCorps1 = tCorpsMapper.checkFNoUnique(tCorps.getfNo());
        if (StringUtils.isNotNull(tCorps1) && !tCorps1.getfId().equals(tCorps.getfId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkUFNnameUnique(TCorps tCorps) {
        TCorps tCorps1 = tCorpsMapper.checkUFNnameUnique(tCorps.getfName());
        if (StringUtils.isNotNull(tCorps1) && !tCorps1.getfId().equals(tCorps.getfId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkUFCnameUnique(TCorps tCorps) {
        TCorps tCorps1 = tCorpsMapper.checkUFCnameUnique(tCorps.getfCname());
        if (StringUtils.isNotNull(tCorps1) && !tCorps1.getfId().equals(tCorps.getfId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkULoginAccountUnique(TCorps tCorps) {
        TCorps corps = tCorpsMapper.checkULoginAccountUnique(tCorps.getLoginAccount());
        if (StringUtils.isNotNull(corps) && !corps.getfId().equals(tCorps.getfId())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public List<Map<String, Object>> selectFleetDriverMsgListMap(TCorps tCorps) {
        return tCorpsMapper.selectFleetDriverMsgListMap(tCorps);
    }

    @Override
    public List<Map<String, Object>> getClientName(TCorps tCorps) {
        return tCorpsMapper.getClientName(tCorps);
    }

}
