package com.dgtly.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dgtly.common.constant.UserConstants;
import com.dgtly.common.core.domain.Ztree;
import com.dgtly.common.exception.BusinessException;
import com.dgtly.common.utils.DateUtils;
import com.dgtly.common.utils.ShiroSaltUtil;
import com.dgtly.common.utils.security.EncryptPassWordClass;
import com.dgtly.companyext.domain.CompanyExamine;
import com.dgtly.companyext.domain.CompanyReviewed;
import com.dgtly.companyext.mapper.CompanyExamineMapper;
import com.dgtly.companyext.mapper.CompanyReviewedMapper;
import com.dgtly.system.domain.SysDept;
import com.dgtly.system.domain.SysUser;
import com.dgtly.system.service.ISysConfigService;
import com.dgtly.system.service.ISysDeptService;
import com.dgtly.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dgtly.system.mapper.SysCompanyMapper;
import com.dgtly.system.domain.SysCompany;
import com.dgtly.system.service.ISysCompanyService;
import com.dgtly.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 公司表Service业务层处理
 * 
 * @author dgtly
 * @date 2020-01-08
 */
@Service
public class SysCompanyServiceImpl implements ISysCompanyService 
{
    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private CompanyReviewedMapper companyReviewedMapper;

    @Autowired
    private CompanyExamineMapper companyExamineMapper;


        /**
         * 查询公司表
         *
         * @param id 公司表ID
         * @return 公司表
         */
    @Override
    public SysCompany selectSysCompanyById(Long id)
    {
        return sysCompanyMapper.selectSysCompanyById(id);
    }

    /**
     * 查询公司表列表
     * 
     * @param sysCompany 公司表
     * @return 公司表
     */
    @Override
    public List<SysCompany> selectSysCompanyList(SysCompany sysCompany)
    {
        return sysCompanyMapper.selectSysCompanyList(sysCompany);
    }

    /**
     * 新增公司表
     * 
     * @param sysCompany 公司表
     * @return 结果
     */
    @Override
    public int insertSysCompany(SysCompany sysCompany)
    {
        sysCompany.setCreateTime(DateUtils.getNowDate());
        return sysCompanyMapper.insertSysCompany(sysCompany);
    }

    /**
     * 修改公司表
     *
     * @param sysCompany 公司表
     * @return 结果
     */
    @Override
    public int updateSysCompany(SysCompany sysCompany)
    {
        sysCompany.setUpdateTime(DateUtils.getNowDate());
        return sysCompanyMapper.updateSysCompany(sysCompany);
    }

    /**
     * 删除公司表对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysCompanyByIds(String ids)
    {
        return sysCompanyMapper.deleteSysCompanyByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除公司表信息
     * 
     * @param id 公司表ID
     * @return 结果
     */
    @Override
    public int deleteSysCompanyById(Long id)
    {
        return sysCompanyMapper.deleteSysCompanyById(id);
    }


    @Override
    @Transactional
    public int addCompany(SysCompany sysCompany,SysUser user){
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserService.checkLoginNameUnique(user.getLoginName())))
        {
            throw  new BusinessException("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }else if (user.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
                || user.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new BusinessException("密码长度为6-19，请重新设置！！");
        }

        sysCompanyMapper.insertSysCompany(sysCompany);
        //创建公司主体部门
        SysDept dept = new SysDept();
        dept.setCompanyId(sysCompany.getId());
        dept.setDeptName(sysCompany.getCompanyName());
        /*父节点为100 总体结构*/
        dept.setParentId(Long.parseLong(sysConfigService.selectConfigByKey("sys.dept.parentId")));
        dept.setCreateBy(sysCompany.getCreateBy());
        sysDeptService.insertDept(dept);
        //创建管理员账号
        user.setSex("1");
        Long[] roles = {Long.parseLong(sysConfigService.selectConfigByKey("company.manager.roleId"))};
        user.setRoleIds(roles);
        user.setDeptId(dept.getDeptId());
        user.setCompanyId(sysCompany.getId());
        user.setSalt(ShiroSaltUtil.randomSalt());
        user.setPassword(EncryptPassWordClass.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(sysCompany.getCreateBy());
        int rows = sysUserService.insertUser(user);
        return rows;
    }

    @Override
    public List<Ztree> selectSysCompanyTree(SysCompany sysCompany) {
        List<SysCompany> companies=sysCompanyMapper.selectSysCompanyList(sysCompany);
        return initZtree(companies);
    }

    /**
     * 查询热门商家列表
     * @param
     * @return
     */
    @Override
    public List<SysCompany> selectCompanyHotList() {
        return sysCompanyMapper.selectCompanyHotList();
    }

    /**
     * 查询公司表排除根目录公司
     * @param:
     * @return:
     * @auther: qxp
     * @date: 2020-2-25
     */
    @Override
    public List<SysCompany> selectSysCompanyListExRoot(SysCompany sysCompany) {
        return sysCompanyMapper.selectSysCompanyListExRoot(sysCompany);
    }



    /**
     * @descption: 树形结构初始化
     * @param:
     * @return:
     * @auther: qxp
     * @date: 2020-2-25
     */
    public List<Ztree> initZtree(List<SysCompany> companies) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (SysCompany company : companies)
        {
            if (UserConstants.DEPT_NORMAL.equals(company.getStatus().toString())&&company.getId()!=1L)
            {
                Ztree ztree = new Ztree();
                ztree.setId(company.getId());
                ztree.setpId(0L);
                ztree.setName(company.getCompanyName());
                ztree.setTitle(company.getCompanyName());
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }



    /**
     * 审核入驻申请通过
     * @param:
     * @return:
     * @auther: qxp
     * @date: 2020-2-25
     */
    @Override
    @Transactional
    public int allowEnter(CompanyExamine companyExamine) {
        /*1.查询公司信息创建SysCompany*/
        /*2.创建部门*/
        /*3.创建管理员*/
        /*4.修改审核信息状态*/
        /*5.插入审核信息*/
        int i = 0;
        CompanyReviewed cr = companyReviewedMapper.selectCompanyReviewedById(companyExamine.getCompanyReviewedId());
        if(cr==null){
            throw  new RuntimeException("创建公司实体时出错!");
        }
        SysCompany company = reviewedTocompany(cr);
        SysUser user= new SysUser();
        user.setLoginName(cr.getLoginName());
        user.setUserName("商户管理员");
        user.setPassword(cr.getPassword());
        user.setPhonenumber(cr.getContactNumber());

        if(addCompany(company,user)>0){
            CompanyReviewed upCr = new CompanyReviewed();
            upCr.setId(cr.getId());
            upCr.setCompanyId(company.getId());
            upCr.setStatus("1");
            upCr.setUpdateBy(companyExamine.getCreateBy());

            i = companyReviewedMapper.updateCompanyReviewed(upCr);
            i +=companyExamineMapper.insertCompanyExamine(companyExamine);
        }else{
            throw new BusinessException("创建公司实体时出错!");
        }
        if(i==2){
            return 1;
        }else{
            throw new BusinessException("创建公司实体时出错!");
        }
    }

    /**
     * 修改商户信息申请通过
     * @param:
     * @return:
     * @auther: qxp
     * @date: 2020-2-25
     */
    @Override
    @Transactional
    public int allowEdit(CompanyExamine companyExamine) {
        /*1.修改公司信息SysCompany*/
        /*2.修改审核信息状态*/
        /*3.插入审核信息*/
        int i = 0;
        CompanyReviewed cr = companyReviewedMapper.selectCompanyReviewedById(companyExamine.getCompanyReviewedId());
        if(cr==null){
            throw  new RuntimeException("创建公司实体时出错!");
        }
        SysCompany company = reviewedTocompany(cr);
        company.setId(cr.getCompanyId());
        company.setUpdateBy(cr.getCreateBy());
        company.setUpdateTime(new Date());
        i = sysCompanyMapper.updateSysCompany(company);
        if(i>0){
            CompanyReviewed upCr = new CompanyReviewed();
            upCr.setId(cr.getId());
            upCr.setCompanyId(cr.getCompanyId());
            upCr.setStatus("1");
            i = companyReviewedMapper.updateCompanyReviewed(upCr);
            i +=companyExamineMapper.insertCompanyExamine(companyExamine);
        }
        if(i==2){
            return 1;
        }else{
            throw new RuntimeException("创建公司实体时出错!");
        }
    }

    public SysCompany reviewedTocompany (CompanyReviewed cr) {
        SysCompany result = new SysCompany();
        result.setCompanyName(cr.getCompanyName());
        result.setStatus(0);
        result.setCompanyType(cr.getCompanyType());
        result.setDetailAddress(cr.getDetailAddress());
        result.setLongitude(cr.getLongitude());
        result.setLatitude(cr.getLatitude());
        result.setLegalPerson(cr.getLegalPerson());
        result.setContactNumber(cr.getContactNumber());
        result.setEstablishDate(cr.getEstablishDate());
        result.setUnifiedSocialCreditCode(cr.getUnifiedSocialCreditCode());
        result.setBusinessLicenseUrl(cr.getBusinessLicenseUrl());
        result.setDefaultImgUrl(cr.getDefaultImgUrl());
        result.setPropagandaImgUrl(cr.getPropagandaImgUrl());
        result.setCompanyIntroduce(cr.getCompanyIntroduce());
        result.setRemark(cr.getRemark());
        result.setPrimaryBusiness(cr.getPrimaryBusiness());
        return result;
    }

    @Override
    public int countCompany() {
        return sysCompanyMapper.countCompany();
    }
}
