package com.fs.company.controller.qw;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.cache.ICompanyUserCacheService;
import com.fs.course.dto.BatchSendCourseDTO;
import com.fs.course.param.FsCourseLinkCreateParam;
import com.fs.course.service.IFsUserCourseService;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;

import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.his.utils.PhoneUtil;
import com.fs.im.dto.OpenImResponseDTO;
import com.fs.im.service.OpenIMService;
import com.fs.qw.domain.CustomerTransferApproval;
import com.fs.qw.domain.CustomerTransferApprovalQw;
import com.fs.qw.dto.FsUserTransferParamDTO;
import com.fs.qw.service.ICustomerTransferApprovalQwService;
import com.fs.qw.service.ICustomerTransferApprovalService;
import com.fs.store.param.h5.FsUserPageListParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

import static com.fs.his.utils.PhoneUtil.encryptPhone;

@Api(tags = "企微会员管理接口")
@RestController
@Slf4j
@RequestMapping("/qw/fsUserByQw")
@AllArgsConstructor
public class FsUserAdminByQwController extends BaseController {

    @Autowired
    private IFsUserService fsUserService;

    @Autowired
    private ICompanyUserCacheService companyUserCacheService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ICustomerTransferApprovalQwService transferApprovalQwService;

    @Autowired
    private IFsUserCourseService fsUserCourseService;

    @Autowired
    private OpenIMService openIMService;

    @PreAuthorize("@ss.hasPermi('user:fsUserQw:list')")
    @PostMapping("/list")
    @ApiOperation("会员列表(与移动端使用的相同查询)")
    public TableDataInfo pageList(@RequestBody FsUserPageListParam param) {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        if(param.getPhone()!=null && !"".equals(param.getPhone())){
            param.setPhone(PhoneUtil.encryptPhone(param.getPhone()));
        }
        return fsUserService.selectFsUserPageListNewQw(param);
    }

    @PreAuthorize("@ss.hasPermi('user:fsUserQw:myList')")
    @PostMapping("/myList")
    @ApiOperation("我的会员列表(与移动端使用的相同查询)")
    public TableDataInfo pageMyList(@RequestBody FsUserPageListParam param) {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(String.valueOf(loginUser.getUser().getUserId()));
        param.setIsAdmin(loginUser.getUser().isAdmin());

        if(param.getCompanyUserId() == null) {
            throw new IllegalArgumentException("当前销售不存在！");
        }
        return fsUserService.selectFsUserPageListNewQw(param);
    }

    /**
     * 转移
     * @param param
     */
    @PostMapping("/transfer")
    @PreAuthorize("@ss.hasPermi('user:fsUserQw:transfer') || @ss.hasPermi('user:fsUserQw:myTransfer') ")
    public R transfer(@RequestBody FsUserTransferParamDTO param){
        log.info("客户转移: {}",param);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setSourceCompanyUserId(loginUser.getUser().getUserId());
        CustomerTransferApprovalQw transferApprovalQw = new CustomerTransferApprovalQw();
        transferApprovalQw.setCorpId(String.valueOf(loginUser.getCompany().getCompanyId()));
        transferApprovalQw.setCustomerIds(JSON.toJSONString(param.getUserIds()));
        transferApprovalQw.setOriginalUserId(param.getSourceCompanyUserId());
        transferApprovalQw.setTargetUserId(param.getTargetCompanyUserId());
        transferApprovalQw.setInitiatorUserId(param.getSourceCompanyUserId());
        transferApprovalQw.setContent(param.getContent());
        transferApprovalQw.setCreatedAt(new Date());
        transferApprovalQw.setUpdatedAt(new Date());
        transferApprovalQw.setApprovalStatus(0);
        transferApprovalQw.setTransferType(2);
        transferApprovalQwService.insertCustomerTransferApprovalQw(transferApprovalQw);
        return R.ok("转移申请已经提交，等待转移成功!");
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return AjaxResult.success(fsUserService.selectFsUserPageListVOByUserIdQw(userId));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('user:fsUserQw:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsUser fsUser)
    {
        return toAjax(fsUserService.updateFsUser(fsUser));
    }


}
