package com.gic.haoban.manage.web.controller.open;

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.JSONResponse;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.AuthorizedUser;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.api.dto.*;
import com.gic.haoban.manage.api.qdto.OpenStaffInitQDTO;
import com.gic.haoban.manage.api.qdto.OpenStaffPageQDTO;
import com.gic.haoban.manage.api.service.OpenStaffApiService;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.web.qo.open.OpenStaffQO;
import com.gic.haoban.manage.web.vo.open.OpenStaffVO;
import com.gic.qcloud.BucketNameEnum;
import com.gic.web.common.download.DownloadTask;
import com.gic.web.common.download.DownloadTaskUtil;
import com.gic.web.common.download.constants.TaskTypeEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企微托管
 */
@RestController
@RequestMapping("/qw-open")
public class QywxOpenController {

    @Autowired
    private OpenStaffApiService openStaffApiService ;
    @Autowired
    private StaffApiService staffApiService ;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService ;
    @Autowired
    private EnterpriseService enterpriseService ;
    @Autowired
    private OpenStaffExcelHandler openStaffExcelHandler ;

    /**
     * 托管列表
     * @param qo
     * @return
     */
    @RequestMapping("open-staff-page")
    public RestResponse<Page<OpenStaffVO>> page(@RequestBody OpenStaffQO qo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        OpenStaffPageQDTO qdto = EntityUtil.changeEntityByJSON(OpenStaffPageQDTO.class,qo) ;
        String enterpriseId = loginUser.getEnterpriseId() ;
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(enterpriseId);
        BasePageInfo basePageInfo = new BasePageInfo() ;
        basePageInfo.setPageNum(qo.getPageNum());
        basePageInfo.setPageSize(qo.getPageSize());
        ServiceResponse<Page<OpenStaffListDTO>> pageResp = this.openStaffApiService.page(qdto, basePageInfo);
        Page<OpenStaffListDTO> page = pageResp.getResult();
        Page<OpenStaffVO> retPage = PageHelperUtils.changePageToCurrentPage(page, OpenStaffVO.class);
        if(CollectionUtils.isNotEmpty(retPage.getResult())) {
            EnterpriseDTO en = this.enterpriseService.getEnterpriseById(enterpriseId) ;
            retPage.getResult().forEach(o->{
                o.setBrandName(en.getBrandName());
            });
        }
        return RestResponse.successResult(retPage);
    }

    /**
     * 托管列表导出
     * @param qo
     * @return
     */
    @RequestMapping("open-staff-excel")
    public RestResponse<String> excel(@RequestBody OpenStaffQO qo) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        OpenStaffPageQDTO qdto = EntityUtil.changeEntityByJSON(OpenStaffPageQDTO.class,qo) ;
        qdto.setWxEnterpriseId(loginUser.getWxEnterpriseId());
        qdto.setEnterpriseId(loginUser.getEnterpriseId());
        BasePageInfo basePageInfo = new BasePageInfo() ;
        basePageInfo.setPageNum(1);
        basePageInfo.setPageSize(1);
        ServiceResponse<Page<OpenStaffListDTO>> pageResp =this.openStaffApiService.page(qdto,basePageInfo) ;
        final int totalCount = pageResp.getResult().getTotalCount() ;
        if (totalCount == 0) {
            return RestResponse.failure("9999", "导出数据条数为0");
        }
        AuthorizedUser user = new AuthorizedUser();
        user.setUserId(loginUser.getClerkId());
        user.setEnterpriseId(loginUser.getEnterpriseId());
        user.setRealName(loginUser.getClerkName());
        Date startDate = new Date();
        Date endDate = new Date() ;
        String fileName = "好办托管企微号"+ "-" + DateUtil.formatString(startDate,"yyyy-MM-dd") + "到" + DateUtil.formatString(endDate,"yyyy-MM-dd");
        // 1.组装数据查询条件
        DownloadTask task = new DownloadTask();
        task.setTaskTypeEnum(TaskTypeEnum.HAOBAN_OPEN_STAFF_LIST);
        task.setUser(user);
        task.setDataType(1);
        task.setTotalCount(totalCount);
        task.setFileName(fileName);
        task.setChannelName(TaskTypeEnum.HAOBAN_OPEN_STAFF_LIST.getName());
        task.setBucketName(BucketNameEnum.REPORT_50000.getName());
        task.setSearchDataParams(JSON.toJSONStringWithDateFormat(qdto, DatePattern.NORM_DATETIME_PATTERN));
        task.setHandler(openStaffExcelHandler);
        JSONResponse jsonResponse = DownloadTaskUtil.createDownloadTask(task);
        final String reportId;
        if (jsonResponse.isSuccess()) {
            reportId = (String) jsonResponse.getResult();
        } else {
            return RestResponse.failure("9999",jsonResponse.getErrorMessage());
        }
        return RestResponse.successResult(reportId);
    }

    /**
     * 登录初始化
     * @param staffId
     * @return
     */
    @RequestMapping("login-init")
    public RestResponse<OpenStaffDTO> init(String staffId , @RequestParam(defaultValue = "0") int loginAgainFlag) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String enterpriseId = login.getEnterpriseId() ;
        if(StringUtils.isBlank(staffId)) {
            return RestResponse.failure("9999","请先选择成员") ;
        }
        StaffDTO staff = this.staffApiService.selectById(staffId) ;
        if(null == staff || !staff.getWxEnterpriseId().equals(wxEnterpriseId)) {
            return RestResponse.failure("9999","成员不存在") ;
        }
        List<StaffClerkRelationDTO> relationList = this.staffClerkRelationApiService.listByStaffId(wxEnterpriseId,staffId) ;
        if(CollectionUtils.isEmpty(relationList)) {
            return RestResponse.failure("9999","成员未关联导购") ;
        }
        relationList = relationList.stream().filter(o->o.getClerkType() <=1 && o.getEnterpriseId().equals(enterpriseId)).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(relationList)) {
            return RestResponse.failure("9999","成员需关联gic商户下导购") ;
        }
        String checkMsg = this.check(wxEnterpriseId,enterpriseId) ;
        if(null != this.check(wxEnterpriseId,enterpriseId)) {
            return RestResponse.failure("9999",checkMsg) ;
        }
        OpenStaffInitQDTO initQDTO = new OpenStaffInitQDTO() ;
        initQDTO.setWxEnterpriseId(wxEnterpriseId);
        initQDTO.setEnterpriseId(enterpriseId);
        initQDTO.setStaffId(staffId);
        initQDTO.setLoginAgainFlag(loginAgainFlag);
        ServiceResponse<Long> resp = this.openStaffApiService.init(initQDTO) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        Long openStaffId = resp.getResult() ;
        return RestResponse.successResult(this.openStaffApiService.getById(openStaffId).getResult());
    }

    /**
     * 获取账号详情
     * @param openStaffId
     * @return
     */
    @RequestMapping("get-open-staff")
    public RestResponse<OpenStaffDTO> getOpenStaff(Long openStaffId) {
        ServiceResponse<OpenStaffDTO> resp = this.openStaffApiService.getById(openStaffId) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 校验验证码
     * @param openStaffId
     * @param code
     * @return
     */
    @RequestMapping("check-code")
    public RestResponse<Void> checkCode(Long openStaffId , String code) {
        ServiceResponse<Void> resp = this.openStaffApiService.checkCode(openStaffId,code) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        return RestResponse.successResult();
    }

    /**
     * 获取2次验证二维码
     * @param openStaffId
     * @return
     */
    @RequestMapping("get-2qrcode")
    public RestResponse<OpenStaffDTO> get2Qrcode(Long openStaffId) {
        ServiceResponse<OpenStaffDTO>  resp = this.openStaffApiService.get2Qrcode(openStaffId) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        return RestResponse.successResult(resp.getResult());
    }

    /**
     * 许可数量查询
     */
    @RequestMapping("license-info")
    public RestResponse<OpenStaffLicenseDTO> licenseInfo() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String enterpriseId = login.getEnterpriseId() ;
        ServiceResponse<OpenStaffLicenseDTO> resp = this.openStaffApiService.getLicenseInfo(wxEnterpriseId,enterpriseId) ;
        if(!resp.isSuccess()) {
            return RestResponse.failure("9999",resp.getMessage()) ;
        }
        return RestResponse.successResult(resp.getResult());
    }

    private String check(String wxEnterpriseId , String enterpriseId) {
        return null ;
    }

}
