package cn.pluss.platform.controller;

import cn.hutool.core.date.DateUtil;
import cn.pluss.platform.activityActivate.ActivityActivateService;
import cn.pluss.platform.activityConsumReturn.ActivityConsumReturnService;
import cn.pluss.platform.activityRecharge.ActivityRechargeService;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.dto.BusinessLicenseDTO;
import cn.pluss.platform.dto.ImgDTO;
import cn.pluss.platform.dto.MerchantBaseInfoDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.mapper.MerchantImageMapper;
import cn.pluss.platform.mapper.MerchantRateMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.BusinessLicenseVO;
import cn.pluss.platform.vo.MerchantBaseInfoVO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author djh
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/merchantBaseInfo")
@Transactional
@Api(value = "商家接口", tags = {"商家接口"})
public class MerchantBaseInfoController {
    private final MerchantBaseInfoService merchantBaseInfoService;
    private final UserAppService userAppService;
    private final MerchantImageMapper merchantImageMapper;
    private final ActivityActivateService activityActivateService;
    private final ActivityConsumReturnService activityConsumReturnService;
    private final ActivityRechargeService activityRechargeService;
    private final UserInfoService userInfoService;
    private final MerchantRateMapper merchantRateMapper;

    private final MerchantChannelStatusService mcsService;

    @GetMapping
    @ApiOperation(value = "获取全部", notes = "返回分页过后的数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "0")})
    public Result<PageInfo<MerchantBaseInfo>> list(@RequestParam(defaultValue = "1") Integer page,
                                                   @RequestParam(defaultValue = "10") Integer size) {
        if (size == null || size == 0) {
            size = ProjectConstant.PAGE_SIZE;
        }
        if (page == null || page == 0) {
            page = 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (page - 1) * size);
        List<MerchantBaseInfo> merchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoPage(map);
        Integer count = merchantBaseInfoService.queryMerchantBaseInfoPageCount(map);
        // 返回参数
        PageInfo<MerchantBaseInfo> pager = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count, size), page.longValue(), size.longValue(),
                merchantBaseInfoList);
        return ResultGenerator.genSuccessResult(pager);
    }

    @PostMapping
    @ApiOperation(value = "添加数据", notes = "添加新的数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantBaseInfo", value = "待添加的MerchantBaseInfo实例", paramType = "body", dataType = "MerchantBaseInfo", required = true)})
    public Result<?> add(@RequestBody MerchantBaseInfo merchantBaseInfo) {
        merchantBaseInfoService.saveMerchantBaseInfo(merchantBaseInfo);
        return ResultGenerator.genSuccessResult();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据", notes = "根据id删除数据", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id实例", paramType = "path", dataType = "Integer", required = true)})
    public Result<?> delete(@PathVariable Long id) {
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setId(id);
        merchantBaseInfoService.deleteMerchantBaseInfo(merchantBaseInfo);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    @ApiOperation(value = "更新数据", notes = "根据内容更新数据", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantBaseInfo", value = "更新的MerchantBaseInfo实例", paramType = "body", dataType = "MerchantBaseInfo", required = true)})
    public Result<?> update(@RequestBody MerchantBaseInfo merchantBaseInfo) {
        merchantBaseInfoService.updateMerchantBaseInfo(merchantBaseInfo);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{merchantCode}")
    @ApiOperation(value = "获取单个值", notes = "查看单个项目的内容", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantCode", value = "查询的MerchantCode", paramType = "path", required = true, dataType = "String", defaultValue = "0")})
    public Result<?> detail(@PathVariable String merchantCode) {
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setMerchantCode(merchantCode);
        merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
        return ResultGenerator.genSuccessResult(merchantBaseInfo);
    }

    @GetMapping("/saveMerchantImg")
    @ApiOperation(value = "保存照片接口", notes = "保存照片接口", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ImgDTO", value = "图片imgdto", paramType = "ImgDTO", dataType = "ImgDTO", required = true),})
    public Result<?> saveMerchantImg(@RequestBody ImgDTO imgDTO) {
        try {
            String userId = imgDTO.getUserId();
            if (StringUtil.isEmpty(userId)) {
                return ResultGenerator.genFailResult("请先登录账号");
            }
            UserApp userApp = new UserApp();
            userApp.setUserId(Long.valueOf(userId));
            List<UserApp> queryUserAppList = userAppService.queryUserAppList(userApp);
            if (queryUserAppList == null || queryUserAppList.size() == 0) {
                return ResultGenerator.genFailResult("无当前账号");
            } else {
                userApp = queryUserAppList.get(0);
            }
            Result<MerchantImage> convertImgDTO = imgDTO.convertImgDTO();
            if (400 == convertImgDTO.getCode()) {
                return convertImgDTO;
            }
            MerchantImage merchantImage = convertImgDTO.getData();
            if (StringUtil.isEmpty(userApp.getMerchantCode())) {
                String merchantCode = "M800" + DateUtil.format(new Date(), "yyyyMMdd") + StringUtil.random6V2();
                merchantImage.setMerchantCode(merchantCode);
                merchantImageMapper.insert(merchantImage);
            } else {
                String merchantCode = userApp.getMerchantCode();
                merchantImage.setMerchantCode(merchantCode);
                MerchantImage mImage = new MerchantImage();
                mImage.setMerchantCode(merchantCode);
                mImage.setPhotoType(imgDTO.getPhoneType());
                List<MerchantImage> queryMerchantImageList = merchantImageMapper.queryMerchantImageList(mImage);
                if (queryMerchantImageList != null && queryMerchantImageList.size() > 0) {
                    merchantImage.setId(queryMerchantImageList.get(0).getId());
                    merchantImageMapper.updateById(merchantImage);
                } else {
                    merchantImageMapper.insert(merchantImage);
                }
            }
            return ResultGenerator.genSuccessResult();
        } catch (NumberFormatException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultGenerator.genFailResult("图片保存失败,请稍后再试");
        }
    }

    @PostMapping("/saveMerchantBaseInfoV2")
    @ApiOperation(value = "添加/修改 商户基本资料", notes = "添加/修改 商户基本资料", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantBaseInfoDTO", value = "MerchantBaseInfoDTO实例", paramType = "body", dataType = "MerchantBaseInfoDTO", required = true)})
    public Result<?> saveMerchantBaseInfoV2(@RequestBody MerchantBaseInfoDTO merchantBaseInfoDTO) {
        try {
            merchantBaseInfoService.saveMerchantBaseInfo(merchantBaseInfoDTO);
            return ResultGenerator.genSuccessResult("保存成功");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultGenerator.genFailResult("系统繁忙，请稍后再试");
        }
    }

    @PostMapping("/saveBusinessLicense")
    @ApiOperation(value = "添加/修改 营业执照", notes = "添加/修改 营业执照", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "", value = "实例", paramType = "body", dataType = "WxCityInfo", required = true)})
    public Result<?> saveBusinessLicense(@RequestBody BusinessLicenseDTO businessLicenseDTO) {
        merchantBaseInfoService.saveBusinessLicense(businessLicenseDTO);
        return ResultGenerator.genSuccessResult("上传营业执照信息成功");
    }

    @GetMapping("/bussAuthDetail")
    @ApiOperation(value = "营业执照信息回显", notes = "营业执照信息回显", httpMethod = "GET")
    public Result<?> aliMerchantInfo(@RequestParam(required = true) String userId) {
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setUserId(userId);
        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService
                .queryMerchantBaseInfoList(merchantBaseInfo);
        if (queryMerchantBaseInfoList == null || queryMerchantBaseInfoList.size() == 0) {
            return ResultGenerator.genSuccessResult();
        }
        merchantBaseInfo = queryMerchantBaseInfoList.get(0);
        MerchantImage merchantImage = new MerchantImage();
        merchantImage.setMerchantCode(merchantBaseInfo.getMerchantCode());
        List<MerchantImage> queryMerchantImageList = merchantImageMapper.queryMerchantImageList(merchantImage);
        BusinessLicenseVO businessLicenseVO = BusinessLicenseVO.convertMerchantBaseInfo(merchantBaseInfo, queryMerchantImageList);
        return ResultGenerator.genSuccessResult(businessLicenseVO);
    }

    @GetMapping(value = "/merchantInfoDetail")
    @ApiOperation(tags = {"页面-首页"}, value = "基本资料回显", notes = "基本资料回显", httpMethod = "GET")
    public Result<?> merchantInfo() {
        UserApp userApp = userAppService.queryUserAppByToken();
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setUserId(userApp.getUserId() + "");
        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(merchantBaseInfo);
        if (queryMerchantBaseInfoList == null || queryMerchantBaseInfoList.size() == 0) {
            return ResultGenerator.genSuccessResult();
        }
        merchantBaseInfo = queryMerchantBaseInfoList.get(0);
        MerchantImage merchantImage = new MerchantImage();
        merchantImage.setMerchantCode(merchantBaseInfo.getMerchantCode());
        List<MerchantImage> queryMerchantImageList = merchantImageMapper.queryMerchantImageList(merchantImage);
        MerchantBaseInfoVO merchantBaseInfoVO = MerchantBaseInfoVO.convertMerchantBaseInfo(merchantBaseInfo, null, queryMerchantImageList);
        return ResultGenerator.genSuccessResult(merchantBaseInfoVO);
    }

    @GetMapping("/queryMerchantActivity")
    @ApiOperation(value = "查询商家活动", notes = "查询商家活动", httpMethod = "POST")
    public Result<?> merchantActivity(@RequestParam String merchantCode) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            ActivityActivate activityActivate = new ActivityActivate();
            activityActivate.setMerchantCode(merchantCode);
            List<ActivityActivate> queryActivityActivateList = activityActivateService
                    .queryActivityActivateList(activityActivate);
            result.put("activityActivateList", queryActivityActivateList);
            ActivityRecharge activityRecharge = new ActivityRecharge();
            activityRecharge.setMerchantCode(merchantCode);
            List<ActivityRecharge> queryActivityRechargeList = activityRechargeService
                    .queryActivityRechargeList(activityRecharge);
            result.put("activityRechargeList", queryActivityRechargeList);
            ActivityConsumReturn activityConsumReturn = new ActivityConsumReturn();
            activityConsumReturn.setMerchantCode(merchantCode);
            List<ActivityConsumReturn> queryActivityConsumReturnList = activityConsumReturnService
                    .queryActivityConsumReturnList(activityConsumReturn);
            result.put("activityConsumReturnList", queryActivityConsumReturnList);
            return ResultGenerator.genSuccessResult(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("系统繁忙，请稍后再试");
        }
    }

    @PostMapping("/manageMerchantManageList")
    @ApiOperation(value = "多商户管理列表", notes = "多商户管理列表", httpMethod = "POST")
    public Result<?> manageMerchantManageList(@RequestBody MerchantBaseInfo merchantBaseInfo) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            List<MerchantBaseInfo> queryMerchantBaseInfoList;
            merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
            if (null != merchantBaseInfo && StringUtil.isNotEmpty(merchantBaseInfo.getBindingCode())) {
                MerchantBaseInfo merchantBaseInfo2 = new MerchantBaseInfo();
                merchantBaseInfo2.setBindingCode(merchantBaseInfo.getBindingCode());
                queryMerchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(merchantBaseInfo2);
            } else {
                queryMerchantBaseInfoList = new ArrayList<>();
                if (merchantBaseInfo != null) {
                    queryMerchantBaseInfoList.add(merchantBaseInfo);
                }
            }

            for (MerchantBaseInfo merchantBaseInfo3 : queryMerchantBaseInfoList) {
                UserInfo userInfo = new UserInfo();
                userInfo.setId(Long.valueOf(merchantBaseInfo3.getUserId()));
                List<UserInfo> queryUserInfoList = userInfoService.queryUserInfoList(userInfo);
                MerchantChannelStatus merchantChannelStatus = mcsService.getValidData(merchantBaseInfo3.getMerchantCode());

                if (merchantChannelStatus == null) {
                    merchantBaseInfo3.setMerchantAuditStatus("0");
                } else {
                    merchantBaseInfo3.setMerchantAuditStatus(merchantChannelStatus.getAppStatus());
                }

                if (queryUserInfoList != null && queryUserInfoList.size() > 0) {
                    userInfo = queryUserInfoList.get(0);
                    merchantBaseInfo3.setLoginName(userInfo.getLoginName());
                    merchantBaseInfo3.setPassword(userInfo.getPassword());
                }

                MerchantImage merchantImage = new MerchantImage();
                merchantImage.setMerchantCode(merchantBaseInfo3.getMerchantCode());
                merchantImage.setPhotoType("06");
                List<MerchantImage> queryMerchantImageList = merchantImageMapper.queryMerchantImageList(merchantImage);
                if (queryMerchantImageList != null && queryMerchantImageList.size() > 0) {
                    merchantImage = queryMerchantImageList.get(0);
                    merchantBaseInfo3.setImgUrl(merchantImage.getPicUrl());
                }
            }
            result.put("merchantBaseInfoList", queryMerchantBaseInfoList);
            return ResultGenerator.genSuccessResult(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("系统异常");
        }
    }

    @PostMapping("/saveMerchantUser")
    @ApiOperation(value = "添加多商户的商户", notes = "添加多商户的商户", httpMethod = "POST")
    public Result<?> saveMerchantUser(@RequestBody MerchantBaseInfoDTO merchantBaseInfoDTO) {
        merchantBaseInfoService.saveMerchantUser(merchantBaseInfoDTO);
        return ResultGenerator.genSuccessResult("子商户添加成功");
    }

    @PostMapping("/saveMerchantUserV2")
    @ApiOperation(value = "添加多商户的商户", notes = "添加多商户的商户", httpMethod = "POST")
    public Result<?> saveMerchantUserV2(@RequestBody MerchantBaseInfoDTO merchantBaseInfoDTO) {
        merchantBaseInfoService.saveMerchantUser(merchantBaseInfoDTO);
        return ResultGenerator.genSuccessResult("子商户添加成功");
    }

    @GetMapping("/mchDetail")
    public Result<MerchantBaseInfoVO> getMchDetail(String userId) {
        MerchantBaseInfoVO mbiVO = merchantBaseInfoService.apiGetMchDetail(userId);
        return ResultGenerator.genSuccessResult(mbiVO);
    }

    @PostMapping("queryFeeInfoByMchId")
    public Result<?> queryFeeInfo(@RequestBody UserApp userApp) {
        UserApp tokenUserApp = userAppService.queryUserAppByToken();
        MerchantRate merchantRate = new MerchantRate().setUserId(tokenUserApp.getUserId() + "");
        merchantRate = merchantRateMapper.selectOne(new QueryWrapper<>(merchantRate));

        Integer rate;
        if (merchantRate != null) {
            rate = merchantRate.getCurrentRate();
        } else {
            rate = 38;
        }

        try {
            if (StringUtil.isNotEmpty(tokenUserApp.getMerchantCode())) {
                MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
                merchantBaseInfo.setMerchantCode(tokenUserApp.getMerchantCode());
                merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
                if (null != merchantBaseInfo) {
                    JSONObject wechatRate = new JSONObject();
                    wechatRate.put("rate", rate);
                    JSONObject alipayRate = new JSONObject();
                    alipayRate.put("rate", rate);
                    JSONObject bank = new JSONObject();
                    bank.put("rate", rate);
                    JSONObject alipayT1 = new JSONObject();
                    alipayT1.put("t1", alipayRate);
                    JSONObject wechatT1 = new JSONObject();
                    wechatT1.put("t1", wechatRate);
                    JSONObject bankT1 = new JSONObject();
                    bankT1.put("t1", bank);
                    JSONObject data = new JSONObject();
                    data.put("alipay", alipayT1);
                    data.put("wechat", wechatT1);
                    data.put("bank", bankT1);
                    return ResultGenerator.genSuccessResult(data);
                } else {
                    return ResultGenerator.genSuccessResult();
                }
            } else {
                return ResultGenerator.genSuccessResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("系统异常");
        }
    }

    @PostMapping("/setVoice")
    @ApiOperation(value = "语音播报开启或关闭", notes = "语音播报开启或关闭", httpMethod = "POST")
    public Result<?> setVoice(@RequestBody MerchantBaseInfo merchantBaseInfo) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantBaseInfo.setMerchantCode(tokenUa.getMerchantCode());
        
        if (StringUtil.isEmpty(merchantBaseInfo.getMerchantCode())) {
            return ResultGenerator.genFailResult("无商家编码");
        }
        if (StringUtil.isEmpty(merchantBaseInfo.getIsVoice())) {
            return ResultGenerator.genFailResult("无是否开启或关闭播报");
        }

        try {
            UserApp userApp = userAppService.queryUserAppByToken();
            userApp.setIsVoice(merchantBaseInfo.getIsVoice());
            userAppService.updateById(userApp);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("系统异常");
        }

    }

    @PostMapping("/switchBankLargePermission")
    @ResponseBody
    public Result<?> switchBankLargePermission() {
        merchantBaseInfoService.apiSwitchBankLargePermission();

        return ResultGenerator.genSuccessResult("操作成功", null);
    }

    @PostMapping("/wxCertPass")
    @ResponseBody
    public Result<?> wxCertPass() {
        merchantBaseInfoService.apiWxCertPass();
        return ResultGenerator.genSuccessResult("操作成功", null);
    }
}
