package com.huyi.service.rel.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huyi.service.base.entity.SysCompany;
import com.huyi.service.base.entity.SysCompanyRel;
import com.huyi.service.base.entity.SysCompanySpare;
import com.huyi.service.base.service.ISysCompanyRelService;
import com.huyi.service.base.service.ISysCompanyService;
import com.huyi.service.base.service.ISysCompanySpareService;
import com.huyi.service.rel.service.IOwnCompanyRelService;
import com.keao.tianhu.starter.mybatis.plus.entity.QueryRequest;
import com.tianhu.common.core.domain.R;
import com.tianhu.common.core.utils.CommonUtil;
import com.tianhu.common.core.utils.DateUtils;
import com.tianhu.common.core.utils.IdUtils;
import com.tianhu.common.core.web.controller.BaseController;
import com.tianhu.common.log.annotation.Log;
import com.tianhu.common.log.enums.BusinessType;
import com.tianhu.common.security.annotation.PreAuthorize;
import com.tianhu.common.security.service.TokenService;
import com.tianhu.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 链属Controller
 * 
 * @author keao
 * @date 2020-12-16
 */
@RestController
@RequestMapping("/rel")
public class OwnCompanyRelController extends BaseController
{
    @Autowired
    private IOwnCompanyRelService iOwnCompanyRelService;

    @Autowired
    private ISysCompanyRelService iSysCompanyRelService;

    @Autowired
    private ISysCompanyService iSysCompanyService;

    @Autowired
    private ISysCompanySpareService iSysCompanySpareService;

    @Autowired
    private TokenService tokenService;

    /**
     * 企业正常状态
     */
    private String NORMAL_STATE = "00";

    /**
     * 停用状态
     */
    private String CONFIRM_STATE = "01";

    /**
     * 拒绝链属
     */
    private String REFUSE_STATE = "02";

    /**
     * 删除状态
     */
    private String DELETE_STATE = "99";

    /**
     * 查询链属列表
     * @param scySocialCode 社会统一信用代码
     * @param companyName   企业名称
     * @param scrType       企业类型
     * @param scrStatus     链属状态
     * @param request
     * @return
     */
    @PreAuthorize(hasPermi = "service:rel:list")
    @GetMapping("/list")
    public R list(String scyId, String scySocialCode, String companyName, String scrType, String scrStatus,QueryRequest request)
    {
        //获取当前操作员
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        Map map = new HashMap();
        if(CommonUtil.isNotEmpty(scyId)){
            map.put("companyId", scyId);
        }
        if(CommonUtil.isEmpty(scyId)) {
            map.put("companyId", companyId);
        }
        if(CommonUtil.isNotEmpty(companyName)) {
            map.put("companyName", companyName);
        }
        if(CommonUtil.isNotEmpty(scySocialCode)) {
            map.put("scySocialCode", scySocialCode);
        }
        if(CommonUtil.isNotEmpty(scrType)) {
            map.put("scrType", scrType);
        }
        if(CommonUtil.isNotEmpty(scrStatus)) {
            map.put("scrStatus", scrStatus);
        }
        IPage<Map> list = iOwnCompanyRelService.selectCompanyRelList(request,map);
        return R.ok(list,companyId);
    }

    /**
     * 查询链属未认证列表
     * @param scySocialCode 社会统一信用代码
     * @param companyName   企业名称
     * @param scrType   企业类型
     * @param request
     * @return
     */
    @PreAuthorize(hasPermi = "service:rel:list")
    @Log(title = "查询链属未认证列表", businessType = BusinessType.OTHER)
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/notCertifiedList")
    public R notCertifiedList(String scySocialCode, String companyName, String scrType, QueryRequest request)
    {
        //获取当前操作员
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        LambdaQueryWrapper<SysCompanySpare> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCompanySpare::getScpCompanyId,companyId);
        //社会统一信用代码
        if(CommonUtil.isNotEmpty(scySocialCode)){
            queryWrapper.like(SysCompanySpare::getScpSocialCode,scySocialCode);
        }
        //企业名称
        if(CommonUtil.isNotEmpty(companyName)){
            queryWrapper.like(SysCompanySpare::getScpName,companyName);
        }
        //企业类型
        if(CommonUtil.isNotEmpty(scrType)){
            queryWrapper.eq(SysCompanySpare::getScpType,scrType);
        }
        queryWrapper.eq(SysCompanySpare::getScpStatus,NORMAL_STATE);
        IPage<SysCompanySpare> notCertifiedList = iSysCompanySpareService.findSysCompanySpares(request,queryWrapper);
        return R.ok(notCertifiedList);
    }

    /**
     * 查询企业列表
     */
    @GetMapping("/companyList")
    @Log(title = "查询企业列表", businessType = BusinessType.OTHER)
    @Transactional(rollbackFor = Exception.class)
    public R companyList(String scyName, String scyType, QueryRequest request)throws Exception {
        //获取当前操作员
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(SysCompany::getScyId,companyId);
        if(CommonUtil.isNotEmpty(scyName)) {
            queryWrapper.like(SysCompany::getScyName, scyName);
        }
        if(CommonUtil.isNotEmpty(scyType)){
            queryWrapper.eq(SysCompany::getScyType,scyType);
        }
        queryWrapper.eq(SysCompany::getScyStatus,NORMAL_STATE);
        IPage<SysCompany> list = iSysCompanyService.findSysCompanys(request,queryWrapper);
        return R.ok(list);
    }

    /**
     * 查询企业
     */
    @GetMapping("/companyListQuery/{scyName}")
    @Log(title = "查询企业列表", businessType = BusinessType.OTHER)
    @Transactional(rollbackFor = Exception.class)
    public R companyListQuery(@PathVariable("scyName") String scyName)throws Exception {
        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCompany::getScyName,scyName);
        queryWrapper.eq(SysCompany::getScyStatus,NORMAL_STATE);
        List<SysCompany> list = iSysCompanyService.findSysCompanys(queryWrapper);
        return R.ok(list);
    }

    /**
     * 新增链属
     */
    @PreAuthorize(hasPermi = "service:rel:add")
    @Log(title = "新增链属信息", businessType = BusinessType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/addCompanyRel")
    public R addCompanyRel(@RequestBody Map<String,Object> map) throws Exception {
        //获取当前操作员
        LoginUser user = tokenService.getLoginUser();
        String companyId = user.getSysUser().getCompanyId();
        String userId = String.valueOf(user.getSysUser().getUserId());

        //链属关系(00:供应商 01:核心企业)
        String scrReceiveType = CommonUtil.objToString(map.get("scrReceiveType"));
        if(CommonUtil.isEmpty(scrReceiveType)){
            throw new Exception("企业类型不能为空");
        }
        //链属企业名称
        String scyName = CommonUtil.objToString(map.get("scyName"));
        if(CommonUtil.isEmpty(scyName)){
            throw new Exception("企业名称不能为空");
        }
        //统一社会信用代码
        String scySocialCode = CommonUtil.objToString(map.get("scySocialCode"));
        if(CommonUtil.isEmpty(scySocialCode)){
            throw new Exception("统一信用代码不能为空");
        }
        //统一信用代码正则校验
        String checkSocialCode = "^([0-9A-HJ-NPQRTUWXY]{2}\\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\\d{14})$";
        Pattern regeSocialCode = Pattern.compile(checkSocialCode);
        Matcher matcherSocialCode = regeSocialCode.matcher(scySocialCode);
        boolean isMatSocialCode = matcherSocialCode.matches();
        if(!isMatSocialCode){
            throw new Exception("统一信用代码格式错误");
        }
        //查询链属企业信息
        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        //统一社会信用代码
        queryWrapper.eq(SysCompany::getScySocialCode,scySocialCode);
        //企业名称
        queryWrapper.like(SysCompany::getScyName,scyName);
        //状态00
        queryWrapper.ne(SysCompany::getScyStatus,DELETE_STATE);
        List<SysCompany> list = iSysCompanyService.findSysCompanys(queryWrapper);
        //链属联系人
        String scrContarct = CommonUtil.objToString(map.get("scrContarct"));
        if(scrContarct.length() > 30){
            throw new Exception("联系人过长");
        }
        //链属联系人手机号
        String scrContarctPhone = CommonUtil.objToString(map.get("scrContarctPhone"));
        if(CommonUtil.isNotEmpty(scrContarctPhone)) {
            if(scrContarctPhone.length() > 11){
                throw new Exception("手机号不能超过11位");
            }
            String checkPhone = "^1[3|4|5|6|7|8|9][0-9]\\d{8}$";
            Pattern regePhone = Pattern.compile(checkPhone);
            Matcher matcherPhone = regePhone.matcher(scrContarctPhone);
            boolean isMatPhone = matcherPhone.matches();
            if (!isMatPhone) {
                throw new Exception("手机格式不正确");
            }
        }
        //链属联系人邮箱
        String scrContarctEmail = CommonUtil.objToString(map.get("scrContarctEmail"));
        if(CommonUtil.isNotEmpty(scrContarctEmail)) {
            String checkEmail = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regeEmail = Pattern.compile(checkEmail);
            Matcher matcherEmail = regeEmail.matcher(scrContarctEmail);
            boolean isMatEmail = matcherEmail.matches();
            if (!isMatEmail) {
                throw new Exception("邮箱格式不正确");
            }
        }
        //创建主键
        String scrId = IdUtils.fastSimpleUUID();
        //链属企业Id
        String scyId = "";
        if(list.size() > 0) {
            scyId = list.get(0).getScyId();
            String finalScyId = scyId;
            //判断两者是否已经链属
            LambdaQueryWrapper<SysCompanyRel> wrapper = new LambdaQueryWrapper<>();
            wrapper.and(i->i.eq(SysCompanyRel::getScrLaunchCompanyId, companyId).or().eq(SysCompanyRel::getScrReceiveCompanyId,  companyId));
            wrapper.and(i->i.eq(SysCompanyRel::getScrLaunchCompanyId, finalScyId).or().eq(SysCompanyRel::getScrReceiveCompanyId, finalScyId));
            wrapper.ne(SysCompanyRel::getScrStatus,DELETE_STATE);
            List<SysCompanyRel> relList = iSysCompanyRelService.findSysCompanyRels(wrapper);
            if(relList.size() > 0){
                throw new Exception("已经和此企业链属，不得重复链属");
            }
            SysCompanyRel sysCompanyRel = new SysCompanyRel();
            //主键
            sysCompanyRel.setScrId(scrId);
            //发起方
            sysCompanyRel.setScrLaunchCompanyId(companyId);
            //接收方
            sysCompanyRel.setScrReceiveCompanyId(scyId);
            //联系人
            sysCompanyRel.setScrContarct(scrContarct);
            //联系电话
            sysCompanyRel.setScrContarctPhone(scrContarctPhone);
            //邮箱
            sysCompanyRel.setScrContarctEmail(scrContarctEmail);
            //链属关系为供应商
            if(NORMAL_STATE.equals(scrReceiveType)) {
                //发起方为核心企业01
                sysCompanyRel.setScrLaunchType(CONFIRM_STATE);
                //接收方为供应商00
                sysCompanyRel.setScrReceiveType(NORMAL_STATE);
                //状态 01:正常
                sysCompanyRel.setScrStatus(CONFIRM_STATE);
            }else if(CONFIRM_STATE.equals(scrReceiveType)){
                //发起方为供应商00
                sysCompanyRel.setScrLaunchType(NORMAL_STATE);
                //接收方为核心企业01
                sysCompanyRel.setScrReceiveType(CONFIRM_STATE);
                //状态 00:待链属
                sysCompanyRel.setScrStatus(NORMAL_STATE);
            }
            //创建者
            sysCompanyRel.setCreateBy(userId);
            //创建时间
            sysCompanyRel.setCreateTime(DateUtils.getNowDate());
            iSysCompanyRelService.createSysCompanyRel(sysCompanyRel);
        } else {
            //新增链属公司信息
            SysCompanySpare sysCompanySpare = new SysCompanySpare();
            sysCompanySpare.setScpId(scrId);
            sysCompanySpare.setScpCompanyId(companyId);
            //企业名称
            sysCompanySpare.setScpName(scyName);
            //统一社会信用代码
            sysCompanySpare.setScpSocialCode(scySocialCode);
            //联系人
            sysCompanySpare.setScpContarct(scrContarct);
            //联系电话
            sysCompanySpare.setScpContarctPhone(scrContarctPhone);
            //邮箱
            sysCompanySpare.setScpContarctEmail(scrContarctEmail);
            //企业类型 00:供应商,01:核心企业
            sysCompanySpare.setScpType(scrReceiveType);
            //状态 00:正常
            sysCompanySpare.setScpStatus(NORMAL_STATE);
            //创建人
            sysCompanySpare.setCreateBy(userId);
            //创建时间
            sysCompanySpare.setCreateTime(DateUtils.getNowDate());
            //todo 短信通知
            iSysCompanySpareService.createSysCompanySpare(sysCompanySpare);
        }
        return R.ok();
    }

    /**
     * 拒绝与同意链属
     * @param map
     * @return
     */
    @PreAuthorize(hasPermi = "service:rel:update")
    @Log(title = "拒绝与删除链属关系", businessType = BusinessType.UPDATE)
    @PutMapping("/updateRel")
    public R updateRel(@RequestBody Map<String,Object> map) throws Exception
    {
        String launchScrId = CommonUtil.objToString(map.get("launchScrId"));
        if(CommonUtil.isEmpty(launchScrId)){
            throw new Exception("要执行信息的主键为空");
        }
        String state = CommonUtil.objToString(map.get("state"));
        if(CommonUtil.isEmpty(state)){
            throw new Exception("要执行信息的状态为空");
        }
        SysCompanyRel sysCompanyRel = new SysCompanyRel();
        //主键
        sysCompanyRel.setScrId(launchScrId);
        //状态01:同意 02:拒绝链属
        sysCompanyRel.setScrStatus(state);
        iSysCompanyRelService.updateById(sysCompanyRel);
        return R.ok();
    }

    /**
     * 删除链属
     * @param launchScrId
     * @return
     */
    @PreAuthorize(hasPermi = "service:rel:delete")
    @Log(title = "删除链属公司", businessType = BusinessType.DELETE)
    @DeleteMapping("/{launchScrId}")
    public R remove(@PathVariable String launchScrId)
    {
        SysCompanyRel sysCompanyRel = new SysCompanyRel();
        //主键
        sysCompanyRel.setScrId(launchScrId);
        //状态99
        sysCompanyRel.setScrStatus(DELETE_STATE);
        iSysCompanyRelService.updateById(sysCompanyRel);
        return R.ok();
    }


    /**
     * 删除链属企业信息数据
     * @param scpId
     * @return
     */
    @PreAuthorize(hasPermi = "service:spare:removeSpare")
    @Log(title = "删除未认证链属公司信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeSpare/{scpId}")
    public R removeSpare(@PathVariable String scpId)
    {
        SysCompanySpare sysCompanySpare = new SysCompanySpare();
        //主键
        sysCompanySpare.setScpId(scpId);
        //状态99
        sysCompanySpare.setScpStatus(DELETE_STATE);
        iSysCompanySpareService.updateById(sysCompanySpare);
        return R.ok();
    }

    /**
     * 查询企业详情
     */
    @GetMapping("/companyDetails")
    @Log(title = "链属企业详情", businessType = BusinessType.OTHER)
    @Transactional(rollbackFor = Exception.class)
    public R companyDetails( String scyId )throws Exception {
        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        if(CommonUtil.isNotEmpty(scyId)) {
            queryWrapper.like(SysCompany::getScyId, scyId);
        }
        List<SysCompany> list = iSysCompanyService.findSysCompanys(queryWrapper);
        return R.ok(list);
    }

    /**
     * 查询企业列表
     */
    @GetMapping("/listAllCompany")
    @Log(title = "所有企业列表", businessType = BusinessType.OTHER)
    @Transactional(rollbackFor = Exception.class)
    public R listAllCompany()throws Exception {
        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCompany::getScyStatus,NORMAL_STATE);
        List<SysCompany> list = iSysCompanyService.findSysCompanys(queryWrapper);
        return R.ok(list);
    }

    /**
     * 获取当前操作员
     * @return
     * @throws Exception
     */
    @GetMapping("/getUser")
    public R getUser()throws Exception {
        //获取当前操作员
        LoginUser user = tokenService.getLoginUser();
        String userId = String.valueOf(user.getSysUser().getUserId());
        return R.ok(userId);
    }

}
