package com.gree.mall.manager.controller.common;

import com.gree.mall.manager.annotation.ApiNotAuth;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.helper.ResponseHelper;
import com.gree.mall.manager.logic.ExpressLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.logic.common.kuaidi100.response.SubscribeResp;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.AdminCompanyWechatService;
import com.gree.mall.manager.plus.service.OrderDetailService;
import com.gree.mall.manager.plus.service.OrderInfoService;
import com.gree.mall.manager.utils.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
@Api(value = "公共API", tags ={"公共API"} )
@RequestMapping(value = "/common", produces = "application/json; charset=utf-8")
public class CommonController {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    ExpressLogic expressLogic;
    @Autowired
    WechatLogic wechatLogic;
//    @Autowired
//    GongdanLogic gongdanLogic;
//    @Autowired
//    AsyncWxTagLogic asyncWxTagLogic;
    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;




    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public ResponseHelper<CommonFile> upload(
            @ApiParam(required = true, value = "附件") @RequestParam(required = true) MultipartFile file
    ) throws IOException, RemoteServiceException {
        CommonFile commonFile = commonLogic.uploadFile(file);
        return ResponseHelper.success(commonFile);
    }

    @GetMapping("/express")
    @ApiOperation(value = "查看物流")
    public ResponseHelper<List<ExpressInfo>> express(
            @ApiParam(required = true, value = "物流单号") @RequestParam(required = true) String logisticsNo,
            @ApiParam(required = false, value = "快递公司code") @RequestParam(required = false) String companyCode
    ) throws IOException, RemoteServiceException {
        List<ExpressInfo> expressInfos = expressLogic.queryExpress(logisticsNo,companyCode);
        return ResponseHelper.success(expressInfos);
    }

    @ApiNotAuth
    @PostMapping("/express/callback")
    @ApiOperation(value = "物流回调")
    public SubscribeResp expressCallback(HttpServletRequest request) throws Exception {
        expressLogic.expressCallBack(request);
        SubscribeResp subscribeResp = new SubscribeResp();
        subscribeResp.setResult(Boolean.TRUE);
        subscribeResp.setReturnCode("200");
        subscribeResp.setMessage("成功");
        return subscribeResp;
    }

    @GetMapping("/express/company")
    @ApiOperation(value = "所有物流公司")
    public ResponseHelper<List<ExpressCompany>> companyList(
    ) throws IOException, RemoteServiceException {
        List<ExpressCompany> expressCompanies = expressLogic.expressCompanyList();
        return ResponseHelper.success(expressCompanies);
    }


    @GetMapping("/region/list")
    @ApiOperation(value = "地区列表")
    public ResponseHelper<List<Region>> regionList(
            @ApiParam(value = "父id(第一级传0)",required = true) @RequestParam(required = true) String pid
    ) throws RemoteServiceException {
        List<Region> list = commonLogic.queryRegionList(pid);
        return ResponseHelper.success(list);
    }


    @GetMapping("/gongdan/smalltype")
    @ApiOperation(value = "工单小类")
    public ResponseHelper<List> regionList(
            @ApiParam(value = "大类",required = false) @RequestParam(required = false) String mainNumber,
            @ApiParam(value = "分类id",required = false) @RequestParam(required = false) String categoryId
    ) throws Exception {

        //List smallType = gongdanLogic.getSmallType(mainNumber,categoryId);
        return ResponseHelper.success(new ArrayList<>());
    }

    @PostMapping("/companywechat/get")
    @ApiOperation("获取商户配置二维码头像等详情")
    public ResponseHelper<AdminCompanyWechat> getCompanyWechat(
            @RequestParam String id
    ){
        AdminCompanyWechat one = adminCompanyWechatService.lambdaQuery()
                //.select(AdminCompanyWechat::getQrcode1, AdminCompanyWechat::getQrcode2)
                .eq(AdminCompanyWechat::getCompanyWechatId, id).one();
        return ResponseHelper.success(one);
    }


//    @GetMapping("/testOrder")
//    @ApiOperation(value = "测试生成安装工单")
//    public ResponseHelper testOrder(
//            @ApiParam(required = true, value = "订单号") @RequestParam(required = true) String orderId,
//            @ApiParam(required = true, value = "大类编号") @RequestParam(required = true) String mainNumber
//    ) throws Exception {
//        OrderInfo orderInfo = orderInfoService.getById(orderId);
//        List<OrderDetail> list = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderId).list();
//        String s = gongdanLogic.installOrder(orderInfo, list, mainNumber);
//        return ResponseHelper.success(s);
//    }


//    @GetMapping("/test2")
//    @ApiOperation(value = "本地成员同步到企业微信")
//    public ResponseHelper test2() throws Exception {
//        //本地的
//        List<EnterpriseWechatWorker20220311> local = enterpriseWechatWorker20220311Service.list();
//        //企微的
//        List<EnterpriseWechatWorker> remote = enterpriseWechatWorkerService.list();
//        List<String> remoteList = remote.stream().map(EnterpriseWechatWorker::getWechatUserId).collect(Collectors.toList());
//        for(EnterpriseWechatWorker20220311 enterpriseWechatWorker : local){
//            //存在则不处理
//            if(remoteList.contains(enterpriseWechatWorker.getWechatUserId())){
//                continue;
//            }
//            //不存在则同步到企业微信
//            workWechatLogic.addWorkUser(enterpriseWechatWorker.getWechatUserId(),enterpriseWechatWorker.getName(),enterpriseWechatWorker.getMobile(),
//                    enterpriseWechatWorker.getGender(),enterpriseWechatWorker.getEmail(),
//                    Long.parseLong(enterpriseWechatWorker.getMainDepartment()),enterpriseWechatWorker.getPosition());
//        }
//        return ResponseHelper.success();
//    }


//    @ApiNotAuth
//    @GetMapping("/external/last")
//    @ApiOperation(value = "获取最新的客户信息")
//    public ResponseHelper<Map<String,Object>> sync(
//            @ApiParam(required = true, value = "企微成员手机号") @RequestParam(required = true) String mobile,
//            @ApiParam(required = false, value = "外部联系人id") @RequestParam(required = false) String externalUserId
//    ) throws WxErrorException {
//        Map<String, Object> lastExternalUser = asyncWxTagLogic.getLastExternalUser(mobile,externalUserId);
//        return ResponseHelper.success(lastExternalUser);
//    }

    @GetMapping("template/download")
    @ApiOperation("下载模板")
    public void download(@RequestParam(required = false) @NotBlank(message = "需下载的模板名称不能为空") String name, HttpServletResponse response) throws IOException {
        CommonUtils.downloadFile(name, response);
    }

    @ApiNotAuth
    @ApiOperation("获取获取前往小程序链接")
    @GetMapping("/getUrlScheme")
    public ResponseHelper<String> getUrlScheme(
            @ApiParam(value = "通过 scheme 码进入小程序时的 query",required = false) @RequestParam(required = false) String query,
            @ApiParam(required = false) @RequestParam(required = false) String companyWechatId
    ) throws IOException, WxErrorException {
        return ResponseHelper.success(wechatLogic.getUrlScheme(query,companyWechatId));
    }

    @ApiNotAuth
    @GetMapping("/img/get")
    @ApiOperation(value = "获取图片")
    public void getImg(
            @ApiParam(required = true, value = "附件key") @RequestParam(required = true) String key,
            HttpServletResponse response
    ) throws IOException, RemoteServiceException {
        String file = commonLogic.getFile(key);
        response.sendRedirect(file);
    }

    @GetMapping("oss/config")
    @ApiOperation(value = "获取oss配置")
    public ResponseHelper<Map<String, String>> getOssConfig() throws UnsupportedEncodingException {
        return ResponseHelper.success(commonLogic.getOSSConfig());
    }


    @GetMapping("/computeVal")
    @ApiOperation(value = "后台计算值", notes = "后台计算值 ", httpMethod = "GET")
    public ResponseHelper<BigDecimal> computeVal(@RequestParam(defaultValue = "0") BigDecimal frontVal,
                                                 @RequestParam(defaultValue = "0") BigDecimal afterVal,
                                                 @RequestParam(defaultValue = "+") String operator,
                                                 @RequestParam(defaultValue = "2") Integer scale,
                                                 @RequestParam(defaultValue = "4", required = false) Integer roundingMode
    ) {
        return ResponseHelper.success(commonLogic.computeVal(frontVal, afterVal, operator, scale, roundingMode));
    }
}
