package com.fs.user;

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.dto.FsUserTransferParamDTO;
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("/user/fsUser")
@AllArgsConstructor
public class FsUserAdminController extends BaseController {

    @Autowired
    private IFsUserService fsUserService;

    @Autowired
    private ICompanyUserCacheService companyUserCacheService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ICustomerTransferApprovalService transferApprovalService;

    @Autowired
    private IFsUserCourseService fsUserCourseService;

    @Autowired
    private OpenIMService openIMService;

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

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
       /* if (param.getIsMyFsUser()){
            param.setCompanyId(loginUser.getCompany().getCompanyId());
            param.setCompanyUserId(String.valueOf(loginUser.getUser().getUserId()));
        }else {
            param.setCompanyId(loginUser.getCompany().getCompanyId());
        }*/
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        if(param.getPhone()!=null && !"".equals(param.getPhone())){
            param.setPhone(PhoneUtil.encryptPhone(param.getPhone()));
        }
//        if(param.getCompanyUserId() == null) {
//            throw new IllegalArgumentException("当前销售不存在！");
//        }
        return fsUserService.selectFsUserPageListNew(param);
    }

    @PreAuthorize("@ss.hasPermi('user:fsUser: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.selectFsUserPageListNew(param);
    }

    @PostMapping("/auditUser")
    @ApiOperation("审核用户（移除小黑屋）")
    public R auditUser(@RequestBody String[] userIds) {
        Boolean r = fsUserService.disabledUser(userIds, true);
        if (r) {
            return R.ok();
        }
        return R.error();
    }

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

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

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


    @ApiOperation("后台会员批量发送课程消息")
    @PostMapping("/batchSendCourse")
    public OpenImResponseDTO batchSendCourse(@RequestBody BatchSendCourseDTO batchSendCourseDTO) throws JsonProcessingException {
        // 生成看课短链
        FsCourseLinkCreateParam fsCourseLinkCreateParam = new FsCourseLinkCreateParam();
        BeanUtils.copyProperties(batchSendCourseDTO, fsCourseLinkCreateParam);
        R courseSortLink = fsUserCourseService.createAppCourseSortLink(fsCourseLinkCreateParam);
        String url = courseSortLink.get("url").toString();
        batchSendCourseDTO.setUrl(url);

        return openIMService.batchSendCourse(batchSendCourseDTO);
    }

}
