package com.huyi.service.conmany.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.SysUserCompanyRel;
import com.huyi.service.base.service.ISysCompanyService;
import com.huyi.service.base.service.ISysUserCompanyRelService;
import com.huyi.service.conmany.service.IOwnCompanyManageService;
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("/company")
public class OwnCompanyManageController extends BaseController
{
    @Autowired
    private ISysUserCompanyRelService iSysUserCompanyRelService;


    @Autowired
    private ISysCompanyService iSysCompanyService;

    @Autowired
    private IOwnCompanyManageService iOwnCompanyManageService;


    @Autowired
    private TokenService tokenService;

    /**
     * 企业四要素认证状态;未认证
     */
    private String NORMAL_STATE = "00";

    /**
     * 企业停用状态;核心企业类型
     */
    private String CONFIRM_STATE = "01";

    /**
     * 企业状态;待四要素认证(认证中)
     */
    private String TREE_STATE = "02";

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

    /**
     * 是经办人
     */
    private String HANDER = "1";

    /**
     * 查询核心企业列表
     * @param sysCompany 企业实体
     * @param request
     * @return
     */
    @PreAuthorize(hasPermi = "service:company:list")
    @GetMapping("/list")
    public R list(SysCompany sysCompany, QueryRequest request)
    {
        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        //企业名称
        if(CommonUtil.isNotEmpty(sysCompany.getScyName())) {
            queryWrapper.like(SysCompany::getScyName, sysCompany.getScyName());
        }
        //企业统一信用代码
        if(CommonUtil.isNotEmpty(sysCompany.getScySocialCode())) {
            queryWrapper.like(SysCompany::getScySocialCode, sysCompany.getScySocialCode());
        }
        //企业联系人（法人）
        if(CommonUtil.isNotEmpty(sysCompany.getScyLegal())) {
            queryWrapper.like(SysCompany::getScyLegal, sysCompany.getScyLegal());
        }
        //企业联系电话
        if(CommonUtil.isNotEmpty(sysCompany.getScyPhone())) {
            queryWrapper.like(SysCompany::getScyPhone, sysCompany.getScyPhone());
        }
        //企业状态不为空
        if(CommonUtil.isNotEmpty(sysCompany.getScyStatus())) {
            if(TREE_STATE.equals(sysCompany.getScyStatus())) {
                queryWrapper.and(i -> i.eq(SysCompany::getScyStatus, TREE_STATE).or().eq(SysCompany::getScyStatus, "03")
                        .or().eq(SysCompany::getScyStatus, "04"));
            }
            if(!TREE_STATE.equals(sysCompany.getScyStatus())){
                queryWrapper.eq(SysCompany::getScyStatus, sysCompany.getScyStatus());
            }
        }
        //企业状态如果为空，则查询正常或停用状态
        if(CommonUtil.isEmpty(sysCompany.getScyStatus())){
            queryWrapper.ne(SysCompany::getScyStatus, DELETE_STATE);
        }
        //企业类型
        if(CommonUtil.isNotEmpty(sysCompany.getScyType())) {
            queryWrapper.eq(SysCompany::getScyType, sysCompany.getScyType());
        }
        IPage<SysCompany> list = iSysCompanyService.findSysCompanys(request,queryWrapper);
        return R.ok(list);
    }

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

        //创建主键
        String scyId = IdUtils.fastSimpleUUID();
        //企业名称
        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("统一信用代码格式错误");
        }
        //联系人
        String scyLegal = CommonUtil.objToString(map.get("scyLegal"));
        if(CommonUtil.isEmpty(scyLegal)){
            throw new Exception("联系人不能为空");
        }
        if(scyLegal.length() > 30){
            throw new Exception("联系人长度不能超过30字；请检查是否正确");
        }
        //联系电话
        String scyPhone = CommonUtil.objToString(map.get("scyPhone"));
        if(CommonUtil.isEmpty(scyPhone)){
            throw new Exception("联系电话不能为空");
        }
        if(CommonUtil.isNotEmpty(scyPhone)) {
            if(scyPhone.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(scyPhone);
            boolean isMatPhone = matcherPhone.matches();
            if (!isMatPhone) {
                throw new Exception("手机格式不正确");
            }
        }
        //执行新增
        SysCompany sysCompany = new SysCompany();
        //主键
        sysCompany.setScyId(scyId);
        //名称
        sysCompany.setScyName(scyName);
        //社会统一代码
        sysCompany.setScySocialCode(scySocialCode);
        //法人
        sysCompany.setScyLegal(scyLegal);
        //联系电话
        sysCompany.setScyPhone(scyPhone);
        //类型（核心企业）
        sysCompany.setScyType(CONFIRM_STATE);
        //企业状态：待四要素状态
        sysCompany.setScyStatus(TREE_STATE);
        //四要素状态：未认证
        sysCompany.setScyAuthStatus(NORMAL_STATE);
        //创建人
        sysCompany.setCreateBy(userId);
        //创建时间
        sysCompany.setCreateTime(DateUtils.getNowDate());
        //新增
        iSysCompanyService.createSysCompany(sysCompany);
        return R.ok();
    }

    /**
     * 获取企业明细信息
     */
    @PreAuthorize(hasPermi = "service:company:query")
    @GetMapping("/{scyId}")
    public R getCompanyInfo(@PathVariable("scyId") String scyId) throws Exception {

        LambdaQueryWrapper<SysCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCompany::getScyId,scyId);
        List<SysCompany> list = iSysCompanyService.findSysCompanys(queryWrapper);
        if(list.size() > 0) {
            if (NORMAL_STATE.equals(list.get(0).getScyAuthStatus())) {
                return R.ok(list);
            }
            if (NORMAL_STATE.equals(list.get(0).getScyStatus())) {
                //经办人信息
                LambdaQueryWrapper<SysUserCompanyRel> sysUserCompanyRel = new LambdaQueryWrapper<>();
                sysUserCompanyRel.eq(SysUserCompanyRel::getSucrCompanyId,scyId);
                sysUserCompanyRel.eq(SysUserCompanyRel::getSucrHandler,HANDER);
                List<SysUserCompanyRel> contactsList = iSysUserCompanyRelService.findSysUserCompanyRels(sysUserCompanyRel);
                List<Map> userList = null;
                List<Map> handlerPositiveList = null;
                List<Map> handlerNegativeList = null;

                Map queryMap = new HashMap();
                queryMap.put("companyId",scyId);
                //发票信息
                List<Map> invoiceList = iOwnCompanyManageService.selectInvoiceList(queryMap);
                //营业执照信息
                List<Map> licenseList = iOwnCompanyManageService.selectLicenseFileList(queryMap);
                //法人证件正面信息
                List<Map> legalFileList = iOwnCompanyManageService.selectLegalFileList(queryMap);
                //法人证件反面信息
                List<Map> legalBackFileList = iOwnCompanyManageService.selectLegalBackFileList(queryMap);
                //法人授权书信息
                List<Map> authorizationList = iOwnCompanyManageService.selectAuthorizationFileList(queryMap);
                //数字证书授权与承诺书信息
                List<Map> commitmentList = iOwnCompanyManageService.selectCommitmentFileList(queryMap);
                //其他附件
                List<Map> appendixList = iOwnCompanyManageService.selectAppendixFileList(queryMap);
                    /*返回结果*/
                    Map map = new HashMap();
                    //基本信息
                    map.put("basicList",list);
                    //经办人信息
                    if(contactsList.size() > 0) {
                        Long sucrUserId = contactsList.get(0).getSucrUserId();
                        Map userMap = new HashMap();
                        userMap.put("userId",sucrUserId);
                        userList = iOwnCompanyManageService.selectUserList(userMap);
                        Map handlerMap = new HashMap();
                        handlerMap.put("userId",sucrUserId);
                        handlerPositiveList  = iOwnCompanyManageService.handlerPositiveList(handlerMap);
                        handlerNegativeList = iOwnCompanyManageService.handlerNegativeList(handlerMap);
                    }
                    map.put("contactsList", userList);
                    //发票信息
                    map.put("invoiceList", invoiceList);
                    //营业执照信息
                    map.put("licenseList",licenseList);
                    //法人证件正面信息
                    map.put("legalList",legalFileList);
                    //法人证件反面信息
                    map.put("legalBackList",legalBackFileList);
                    //经办人证件正面信息
                    map.put("handlerPositiveList",handlerPositiveList);
                    //经办人证件反面信息
                    map.put("handlerNegativeList",handlerNegativeList);
                    //法人授权书信息
                    map.put("authorizationList",authorizationList);
                    //数字证书授权与承诺书信息
                    map.put("commitmentList",commitmentList);
                    //其他附件
                    map.put("appendixList",appendixList);
                return R.ok(map);
            }
        }else {
            throw new Exception("企业不存在");
        }
        return R.ok();
    }

    /**
     * 修改企业信息
     */
    @PreAuthorize(hasPermi = "service:company:update")
    @Log(title = "平台修改未认证企业信息", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/updateCompany")
    public R updateCompany(@RequestBody Map<String,Object> map) throws Exception {
        //获取当前操作员
        LoginUser user = tokenService.getLoginUser();
        String userId = String.valueOf(user.getSysUser().getUserId());

        //主键
        String scyId = CommonUtil.objToString(map.get("scyId"));
        if(CommonUtil.isEmpty(scyId)){
            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("统一信用代码格式错误");
        }
        //联系人
        String scyLegal = CommonUtil.objToString(map.get("scyLegal"));
        if(CommonUtil.isEmpty(scyLegal)){
            throw new Exception("联系人不能为空");
        }
        if(scyLegal.length() > 30){
            throw new Exception("联系人长度不能超过30字；请检查是否正确");
        }
        //联系电话
        String scyPhone = CommonUtil.objToString(map.get("scyPhone"));
        if(CommonUtil.isEmpty(scyPhone)){
            throw new Exception("联系电话不能为空");
        }
        if(CommonUtil.isNotEmpty(scyPhone)) {
            if(scyPhone.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(scyPhone);
            boolean isMatPhone = matcherPhone.matches();
            if (!isMatPhone) {
                throw new Exception("手机格式不正确");
            }
        }
        //查询当前企业id的状态
        SysCompany sysCompanyQuery = iSysCompanyService.getById(scyId);
        //执行修改
        SysCompany sysCompany = new SysCompany();
        //主键
        sysCompany.setScyId(scyId);
        //名称
        sysCompany.setScyName(scyName);
        //社会统一代码
        sysCompany.setScySocialCode(scySocialCode);
        //法人
        sysCompany.setScyLegal(scyLegal);
        //联系电话
        sysCompany.setScyPhone(scyPhone);
        //类型（核心企业）
        sysCompany.setScyType(sysCompanyQuery.getScyType());
        //企业状态
        sysCompany.setScyStatus(sysCompanyQuery.getScyStatus());
        //四要素状态
        sysCompany.setScyAuthStatus(sysCompanyQuery.getScyAuthStatus());
        //创建人
        sysCompany.setCreateBy(userId);
        //创建时间
        sysCompany.setCreateTime(DateUtils.getNowDate());
        //修改
        iSysCompanyService.updateById(sysCompany);
        return R.ok();
    }


    /**
     * 修改企业详情信息
     */
    @PreAuthorize(hasPermi = "service:company:update")
    @Log(title = "平台修改认证企业信息", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/updateCompanyInfor")
    public R updateCompanyInfor(@RequestBody Map<String,Object> map) throws Exception {
        //获取当前操作员
        LoginUser user = tokenService.getLoginUser();
        String userId = String.valueOf(user.getSysUser().getUserId());

        //主键
        String scyId = CommonUtil.objToString(map.get("scyId"));
        if(CommonUtil.isEmpty(scyId)){
            throw new Exception("修改的企业编号不能为空");
        }
        //所属行业
        String scyIndustry = CommonUtil.objToString(map.get("scyIndustry"));
        //企业规模
        String scyScale = CommonUtil.objToString(map.get("scyScale"));
        //机构性质
        String scyOrganization = CommonUtil.objToString(map.get("scyOrganization"));
        //客户经理
        String scyManager = CommonUtil.objToString(map.get("scyManager"));
        //执行修改
        SysCompany sysCompany = new SysCompany();
        //主键
        sysCompany.setScyId(scyId);
        //所属行业
        sysCompany.setScyIndustry(scyIndustry);
        //企业规模
        sysCompany.setScyScale(scyScale);
        //机构性质
        sysCompany.setScyOrganization(scyOrganization);
        //客户经理
        sysCompany.setScyManager(scyManager);
        sysCompany.setUpdateBy(userId);
        sysCompany.setUpdateTime(DateUtils.getNowDate());
        iSysCompanyService.updateById(sysCompany);
        return R.ok();
    }

    /**
     * 冻结或解冻企业
     */
    @PreAuthorize(hasPermi = "service:company:updateCompanyStatus")
    @Log(title = "平台修改冻结或解冻企业信息", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/updateCompanyStatus")
    public R updateCompanyStatus(@RequestBody Map<String,Object> map) throws Exception {
        //主键
        String scyId = CommonUtil.objToString(map.get("scyId"));
        if(CommonUtil.isEmpty(scyId)){
            throw new Exception("要执行信息的主键为空");
        }
        //状态
        String state = CommonUtil.objToString(map.get("state"));
        if(CommonUtil.isEmpty(state)){
            throw new Exception("要执行信息的状态为空");
        }
        //执行
        SysCompany sysCompany = new SysCompany();
        sysCompany.setScyId(scyId);
        sysCompany.setScyStatus(state);
        iSysCompanyService.updateById(sysCompany);
        return R.ok();
    }

    /**
     * 四要素人工审核
     */
    @PreAuthorize(hasPermi = "service:company:elementStatus")
    @Log(title = "平台人工审核企业四要素", businessType = BusinessType.UPDATE)
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/elementStatus")
    public R elementStatus(@RequestBody Map<String,Object> map) throws Exception {
        //获取当前操作员
        LoginUser user = tokenService.getLoginUser();
        String userId = String.valueOf(user.getSysUser().getUserId());
        //主键
        String scyId = CommonUtil.objToString(map.get("scyId"));
        if(CommonUtil.isEmpty(scyId)){
            throw new Exception("要执行信息的企业为空");
        }
        //状态
        String state = CommonUtil.objToString(map.get("state"));
        if(CommonUtil.isEmpty(state)){
            throw new Exception("要执行信息的状态为空");
        }
        //执行
        SysCompany sysCompany = new SysCompany();
        sysCompany.setScyId(scyId);
        sysCompany.setScyStatus(state);
        sysCompany.setUpdateBy(userId);
        sysCompany.setUpdateTime(DateUtils.getNowDate());
        iSysCompanyService.updateById(sysCompany);
        return R.ok();
    }

    /**
     * 删除企业
     * @param scyId
     * @return
     */
    @PreAuthorize(hasPermi = "service:company:delete")
    @Log(title = "删除企业信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{scyId}")
    public R removeCompany(@PathVariable String scyId)
    {
        SysCompany sysCompany = new SysCompany();
        //主键
        sysCompany.setScyId(scyId);
        //状态99
        sysCompany.setScyStatus(DELETE_STATE);
        iSysCompanyService.updateById(sysCompany);
        return R.ok();
    }

}
