package com.fs.app.controller;

import cn.hutool.json.JSONUtil;
import com.fs.app.params.LoginBindCompanyParam;
import com.fs.common.BeanCopyUtils;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.R;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.CustomException;
import com.fs.common.exception.base.BaseException;
import com.fs.common.param.LoginParam;
import com.fs.common.utils.PatternUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyUser;
import com.fs.company.param.CompanyUserCodeParam;
import com.fs.company.service.ICompanyPostService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.qw.domain.QwExternalContactInfo;
import com.fs.qw.domain.QwTagGroup;
import com.fs.qw.param.ExternalContactDetailsParam;
import com.fs.qw.param.QwExtCourseSopWatchLog;
import com.fs.qw.param.sidebar.ExternalContactInfoParam;
import com.fs.qw.param.sidebar.TagGroupListParam;
import com.fs.qw.param.sidebar.TagGroupUpdateParam;
import com.fs.qw.service.IQwExternalContactInfoService;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwTagGroupService;
import com.fs.qw.vo.ExternalContactDetailsVO;
import com.fs.qw.vo.QwTagGroupListVO;
import com.fs.qw.vo.sidebar.ExternalContactInfoVO;
import com.fs.qw.vo.sidebar.ExternalContactTagVO;
import com.fs.sop.service.ISopUserLogsInfoService;
import com.fs.sop.vo.ExtCourseSopWatchLogVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "企微会员相关接口")
@RestController
@RequestMapping("/app/qw/user")
public class QwUserController extends BaseController {

    @Autowired
    private IQwExternalContactService qwExternalContactService;

    @Autowired
    private IQwExternalContactInfoService qwExternalContactInfoService;

    @Autowired
    private IQwTagGroupService qwTagGroupService;

    @Autowired
    private ISopUserLogsInfoService iSopUserLogsInfoService;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    ICompanyUserService userService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    ICompanyPostService postService;

    @GetMapping("/details")
    @ApiOperation("会员看课详情")
    public R getUserDetails(@ApiParam(value = "外部联系人id", required = true) @RequestParam Long contactId,
                            @ApiParam(value = "时间tab，不传表示查询全部，分别是：今天、昨天、前天、近七天", required = true) String dateTag) {
        ExternalContactDetailsParam param = new ExternalContactDetailsParam();
        param.setUserId(getUserId());
        param.setContactId(contactId);
        param.setDateTag(dateTag);
        ExternalContactDetailsVO userDetails = qwExternalContactService.getUserDetails(param);
        Map<String, Object> map = new HashMap<>();
        map.put("userDetails", userDetails);
        return R.ok(map);
    }


    @GetMapping("/getQwUserInfo")
    @ApiOperation("获取企微用户信息")
    public R getQwUserInfo(@RequestParam(value = "qwExternalContactId",required = false) Long qwExternalContactId){
        if(qwExternalContactId == null) {
            throw new CustomException("企微外部联系人id不能为空!");
        }
//        QwExternalContact qwExternalContact = qwExternalContactService.selectQwExternalContactById(qwExternalContactId);
        QwExternalContactInfo contactInfo = qwExternalContactInfoService.selectQwExternalContactInfoByExternalContactId(qwExternalContactId);
        if (contactInfo==null){

            contactInfo = new QwExternalContactInfo();
            contactInfo.setExternalContactId(qwExternalContactId);
            qwExternalContactInfoService.insertQwExternalContactInfo(contactInfo);

        }

//        return R.ok().put("data",qwExternalContact).put("moreInfo",contactInfo);
        return R.ok().put("moreInfo",contactInfo);
    }

    @PostMapping("/updateQwUserInfo")
    @ApiOperation("更新企微用户信息")
    public R updateQwUserInfo(@RequestBody QwExternalContactInfo qwExternalContactInfo){
        if(qwExternalContactInfo.getExternalContactId() == null) {
            throw new CustomException("企微外部联系人id不能为空!");
        }
        qwExternalContactInfoService.updateQwExternalContactInfoByExternalContactId(qwExternalContactInfo);
        return R.ok();
    }

    @PostMapping("/extCourseSopWatchLog")
    @ApiOperation("获取外部联系人按照 营期天数 获取到的今天该看的课")
    public R getExtCourseSopWatchLog(@RequestBody QwExtCourseSopWatchLog param) {

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<ExtCourseSopWatchLogVO> list = iSopUserLogsInfoService.getExtCourseSopWatchLog(param);
        PageInfo<ExtCourseSopWatchLogVO> result = new PageInfo<>(list);

        return R.ok().put("data", result);
    }

    @GetMapping("/externalContact")
    @ApiOperation("获取侧边栏外部联系人信息")
    public R getExternalContactInfo(@RequestParam(value = "qwExternalContactId") Long qwExternalContactId) {
        ExternalContactInfoVO externalContactInfo = qwExternalContactService.getExternalContactInfo(qwExternalContactId);
        return R.ok().put("data", externalContactInfo);
    }


    @GetMapping("/externalContact/tag")
    @ApiOperation("获取侧边栏外部联系人标签")
    public R getExternalContactTag(@RequestParam(value = "qwExternalContactId") Long qwExternalContactId) {
        List<ExternalContactTagVO> tagList = qwExternalContactService.getExternalContactTag(qwExternalContactId);
        return R.ok().put("data", tagList);
    }

    @PutMapping("/externalContact")
    @ApiOperation("编辑外部联系人信息")
    public R updateExternalContactInfo(@RequestBody ExternalContactInfoParam param) {
        return qwExternalContactService.updateExternalContactInfo(param);
    }

    @GetMapping("/tagGroupList")
    @ApiOperation("获取所有标签组和其下标签")
    public R getTagGroupList(TagGroupListParam param) {
        QwTagGroup qwTagGroup = new QwTagGroup();
        BeanCopyUtils.copy(param, qwTagGroup);
        qwTagGroup.setName(param.getTagName());

        PageHelper.startPage(qwTagGroup.getPageNum(), qwTagGroup.getPageSize());
        List<QwTagGroupListVO> list = qwTagGroupService.selectQwGroupTagList(qwTagGroup);

        PageInfo<QwTagGroupListVO> result = new PageInfo<>(list);
        return R.ok().put("data", result);
    }


    @PutMapping("/externalContact/tag")
    @ApiOperation("编辑标签")
    public R updateExternalContactTag(@RequestBody TagGroupUpdateParam param) {
        int i = qwExternalContactService.updateExternalContactTag(param);
        if (i > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
    * 注册或者绑定销售
    */
    @PostMapping("/registerCompany")
    @Log(title = "注册或者绑定销售", businessType = BusinessType.INSERT)
    public R registerCompany(@RequestBody CompanyUserCodeParam userCodeParam) {
        return companyUserService.registerCompany(userCodeParam);
    }

    @PostMapping("/login")
    @ApiOperation("密码登录")
    public R login(@Validated @RequestBody LoginBindCompanyParam param) {

        // 密码校验
        if (!PatternUtils.checkPassword(param.getPassword())) {
            return R.error("密码格式不正确,需包含字母、数字和特殊字符,长度为 8-20位");
        }

        try {

            //判断用户基本规则
            CompanyUser companyUser = userService.selectUserByUserName(param.getAccount());
            if (companyUser == null) {
                return R.error("工号不存在");
            }
            if (companyUser.getStatus().equals("1")) {
                return R.error("用户已禁用");
            }
            if (!SecurityUtils.matchesPassword(param.getPassword(), companyUser.getPassword())) {
                return R.error("密码错误");
            }
            if (companyUser.getIsAudit() == 0) {
                return R.error("用户未审核");
            }

            Company company = companyService.selectCompanyById(companyUser.getCompanyId());
            if (company == null || company.getStatus() == 0 || company.getIsDel() == 1) {
                throw new BaseException("此用户所属公司不存在或已停用");
            }

            return R.ok("验证成功");
        } catch (Exception e) {
            return R.error("登录异常:"+e.getMessage());
        }
    }
}
