package cn.pluss.platform.controller.merchantStore;

import cn.pluss.platform.annotation.PassToken;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.common.CommonRemarkService;
import cn.pluss.platform.controller.BaseNoModelController;
import cn.pluss.platform.entitiy.ShiroUser;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.mapper.MerchantChannelStatusMapper;
import cn.pluss.platform.mapper.OperationRecordMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchant.MerchantPluginService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantImage.MerchantImageService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.operationRecord.OperationRecordService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.vo.StoreInfoVO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutorService;

@Slf4j
@Controller
@RequestMapping("merchantStore")
public class MerchantStoreController extends BaseNoModelController {

    @Setter(onMethod_ = {@Autowired})
    private HttpServletRequest request;

    @Setter(onMethod_ = {@Autowired})
    private MerchantStoreService merchantStoreService;

    @Setter(onMethod_ = {@Autowired})
    private OperationRecordService operationRecordService;

    @Resource
    private OperationRecordMapper opRecordMapper;

    @Setter(onMethod_ = {@Autowired})
    private MerchantBaseInfoService merchantBaseInfoService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantChannelStatusService mcsService;

    @Autowired
    private MerchantChannelStatusMapper mcsMapper;

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantPluginService merchantPluginService;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private MerchantImageService merchantImageService;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    private CommonRemarkService remarkService;


    @Setter(onMethod_ = {@Autowired, @Qualifier("ysAuditServiceV2")})
    private MerchantAuditService ysAuditServiceV2;


    /**
     * 引导页
     */
    @GetMapping(value = "/index")
    public String index() {
        return "merchantStore/merchantStoreList";
    }

    /**
     * 分页查询
     */
    @RequestMapping(value = "/queryMerchantStoreByPage", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String, Object> queryMerchantStoreByPage(@RequestParam(defaultValue = "1") Integer currPage,
                                                        Integer size, MerchantStore merchantStore, MerchantBaseInfo merchantBaseInfo, String merchantType, String userId) {
        return merchantStoreService.queryMerchantStoreByPage(currPage, size, merchantStore, merchantBaseInfo, merchantType, userId);
    }

    @GetMapping(value = "/merchantStoreForbidden")
    public ModelAndView forbidden(@RequestParam(value = "id") Integer id, String resultValue, ModelAndView view) {
        view.setViewName("merchantStore/merchantStoreForbidden");
        view.addObject("resultValue", resultValue);
        view.addObject("id", id);
        return view;
    }

    @PostMapping(value = "/disableMerchantStore")
    @ResponseBody
    public Map<String, Object> disableMerchantStore(Integer id, String resultValue, String remark) {
        ShiroUser shiroUser = queryCurrentShiroUser();
        Map<String, Object> params = new HashMap<>(2);
        OperationRecord operationRecord = new OperationRecord();
        operationRecord.setOperator(String.valueOf(shiroUser.getId()));
        //封装被操作人ID
        operationRecord.setUserId(String.valueOf(id));
        operationRecord.setCreateTime(new Date());
        operationRecord.setRemark(remark);

        if ("2".equals(resultValue)) {
            merchantStoreService.enableMerchantStore(shiroUser.getId(), id.longValue(), remark);
        } else if ("1".equals(resultValue)) {
            merchantStoreService.disableMerchantStore(shiroUser.getId(), id.longValue(), remark);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("msg", "保存成功!");
        return result;
    }

    @GetMapping(value = "/merchantStorePath")
    public String merchantStorePath() {
        String ids = request.getParameter("id");
        Integer id = Integer.valueOf(ids);
        System.out.println("id=" + id);
        request.setAttribute("id", id);
        return "merchantStore/merchantStoreParticulars";
    }

    @PostMapping(value = "/queryMerchantStoreParticulars")
    @ResponseBody
    public Map<String, Object> queryMerchantStoreParticulars(@RequestParam(defaultValue = "1") Integer currPage, @RequestParam Integer id) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        int pageSize = 12;
        map.put("pageSize", pageSize);
        map.put("offset", (currPage - 1) * pageSize);
        map.put("id", id);
        List<OperationRecord> operationRecordList = operationRecordService.selectOne(map);
        Integer count = operationRecordService.selectParticularsCount(map);
        boolean admin = verifyUserRole();
        result.put("admin", admin);
        result.put("operationRecordList", operationRecordList);
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count, pageSize));
        result.put("currPage", currPage);
        return result;
    }

    @PostMapping(value = "/merchantStorePayEcdemicSwitch")
    @ResponseBody
    public Map<String, Object> selectPayEcdemicSwitch(@RequestParam(value = "id") Integer id) {
        StoreInfoVO storeInfoVO = merchantStoreService.selectParticulars(id);
        if (storeInfoVO == null) {
            storeInfoVO = new StoreInfoVO();
        }

        String payEcdemicSwitch = storeInfoVO.getPayEcdemicSwitch();
        if (payEcdemicSwitch == null) {
            payEcdemicSwitch = "0";
        }
        Map<String, Object> result = new HashMap<>();
        result.put("payEcdemicSwitch", payEcdemicSwitch);
        result.put("resultCode", "1");
        result.put("msg", "保存成功!");
        return result;
    }

    @PostMapping(value = "/updateChannelStatus")
    @ResponseBody
    public Result<?> updateChannelStatus(@RequestParam(value = "csId") Integer csId, @RequestParam(value = "status") String status) {
        MerchantChannelStatus channelStatus = new MerchantChannelStatus();
        channelStatus.setId(csId);
        channelStatus = mcsService.getByIdLock(csId);
        merchantStoreService.updateChannelStatusAndWxCert(channelStatus, status);
        return ResultGenerator.genSuccessResult("操作成功", null);
    }

    @GetMapping(value = "/merchantStoreThoroughfare")
    public ModelAndView thoroughfare(Integer id, String payEcdemicSwitch, ModelAndView view) {
        view.setViewName("merchantStore/merchantStoreTthoroughfare");
        view.addObject("payEcdemicSwitch", payEcdemicSwitch);
        view.addObject("id", id);
        return view;
    }

    @PostMapping(value = "/payEcdemicSwitchMerchantStore")
    @ResponseBody
    public Map<String, Object> payEcdemicSwitchMerchantStore(@RequestParam(value = "id") Integer id, String payEcdemicSwitch, String remark) {
        ShiroUser shiroUser = queryCurrentShiroUser();
        Map<String, Object> params = new HashMap<>(2);
        OperationRecord operationRecord = new OperationRecord();
        operationRecord.setOperator(String.valueOf(shiroUser.getId()));
        //封装被操作人ID
        operationRecord.setUserId(String.valueOf(id));
        operationRecord.setCreateTime(new Date());
        operationRecord.setRemark(remark);
        if ("1".equals(payEcdemicSwitch)) {
            payEcdemicSwitch = "0";
            operationRecord.setDictValue("GBGRDZWL");
        } else if ("0".equals(payEcdemicSwitch)) {
            payEcdemicSwitch = "1";
            operationRecord.setDictValue("KTGRDZWL");
        }
        opRecordMapper.insert(operationRecord);
        params.put("id", id);
        params.put("payEcdemicSwitch", payEcdemicSwitch);
        merchantStoreService.pesUpdateMerchantStore(params);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("msg", "保存成功!");
        return result;
    }

    @PostMapping(value = "/operatMarket")
    @ResponseBody
    public Map<String, Object> operateMarket(@RequestParam(value = "ids[]") Integer[] ids, String isMarker) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("ids", ids);
        params.put("isMarker", isMarker);
        merchantStoreService.operatMarketMerchantStore(params);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("msg", "保存成功!");
        return result;
    }

    @PostMapping("/queryStatus")
    @ResponseBody
    public Map<String, Object> queryStatus(@RequestParam(value = "id") Integer id) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("id", id);
        StoreInfoVO storeInfoVO = merchantStoreService.selectStatus(params);
        int resultValue;
        if ("2".equals(storeInfoVO.getStatus())) {
            resultValue = 2;
        } else {
            resultValue = 1;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultValue", resultValue);
        result.put("msg", "保存成功!");
        return result;
    }

    /**
     * 查询详情
     */
    @GetMapping("/queryMerchantStoreDetails")
    public String queryMerchantStoreDetails(HttpServletRequest request, Integer id, Integer pageIndex) {

        if (id != null && id != 0) {
            MerchantStore merchantStore = new MerchantStore();
            merchantStore.setId(id);
            merchantStore = merchantStoreService.queryMerchantStore(merchantStore);
            request.setAttribute("merchantStore", merchantStore);
            request.setAttribute("pageIndex", pageIndex);
        }
        return "merchantStore/merchantStoreDetails";
    }

    /**
     * 查询详情
     */
    @GetMapping("/showMerchantStoreReceipt")
    @ResponseBody
    public Map<String, Object> showMerchantStoreReceipt(Integer userId, Integer channel) {
        Map<String, Object> result = new HashMap<>(3);
        if (userId != null && userId != 0) {
            StoreInfoVO queryStoreInfoVO = merchantStoreService.showMerchantStoreReceipt(userId);
            String url = ParametersUtil.domain + "/wap/merchant/authPay?userAppId=" + queryStoreInfoVO.getUserId() + "&channel=" + channel;
            result.put("url", url);
            result.put("storeName", queryStoreInfoVO.getStoreName());
            result.put("code", "1");
            result.put("msg", "获取成功！");
            return result;
        }
        result.put("code", "0");
        result.put("msg", "获取失败！");
        return result;
    }

    /**
     * 查询详情
     */
    @GetMapping("/queryMerchantStoreBaseInfo")
    public String queryMerchantStoreBaseInfo(HttpServletRequest request, Integer id, Integer pageIndex) {
        MerchantStore merchantStore = new MerchantStore();
        ShiroUser user = queryCurrentShiroUser();
        if (id != null && id != 0) {
            merchantStore.setId(id);
            merchantStore = merchantStoreService.queryMerchantStore(merchantStore);
            request.setAttribute("merchantStore", merchantStore);
            request.setAttribute("pageIndex", pageIndex);
        } else {
            //添加时存入MerchantCode商户编码 前台根据有无判断是否有资格添加门店
            merchantStore.setMerchantCode(user.getMerchantCode());
            request.setAttribute("merchantStore", merchantStore);
        }
        getRole();
        List<MerchantBaseInfo> merchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(null);
        request.setAttribute("merchantBaseInfoList", merchantBaseInfoList);
        return "merchantStore/merchantStoreBaseInfo";
    }

    /**
     * 保存对象
     */
    @PostMapping("/saveMerchantStore")
    @ResponseBody
    public Map<String, Object> saveMerchantStore(MerchantStore merchantStore) {
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();

        if (merchantStore.getId() != null && merchantStore.getId() != 0) {
            List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(merchantBaseInfo);
            if (queryMerchantBaseInfoList != null && !queryMerchantBaseInfoList.isEmpty()) {
                merchantBaseInfo = queryMerchantBaseInfoList.get(0);
                merchantStore.setEmail(merchantBaseInfo.getEmail());
                merchantStore.setMerchantName(merchantBaseInfo.getMerchantName());
            }
        } else {
            //不管是不是管理员的增加
            merchantStore.setStoreId(StringUtil.genRandomNum(5));
            List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(merchantBaseInfo);
            if (queryMerchantBaseInfoList != null && !queryMerchantBaseInfoList.isEmpty()) {
                merchantBaseInfo = queryMerchantBaseInfoList.get(0);
                merchantStore.setEmail(merchantBaseInfo.getEmail());
                merchantStore.setMerchantName(merchantBaseInfo.getMerchantName());
            }
        }
        Map<String, Object> result = new HashMap<>();
        //判断是否是管理员
        if (merchantStore.getId() != null && merchantStore.getId() != 0) {
            merchantStoreService.updateMerchantStore(merchantStore);
        } else {
            merchantStoreService.saveMerchantStore(merchantStore);
        }

        return result;
    }

    /**
     * 修改对象
     */
    @PostMapping("/updateMerchantStore")
    @ResponseBody
    public Map<String, Object> updateMerchantStore(Integer id) {

        MerchantStore merchantStore = new MerchantStore();
        merchantStore.setId(id);
        merchantStoreService.updateMerchantStore(merchantStore);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 删除对象
     */
    @PostMapping("/deleteMerchantStore")
    @ResponseBody
    public Map<String, Object> deleteMerchantStore(Integer id) {
        MerchantStore merchantStore = new MerchantStore();
        merchantStore.setId(id);
        merchantStoreService.deleteMerchantStore(merchantStore);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }


    /**
     * 手动后台发起进件
     */
    @PassToken
    @GetMapping(value = "/manualMerchantIncom/{userId}/{id}/{merchantCode}")
    @ResponseBody
    public Map<String, Object> manualMerchantIncome(@PathVariable("userId") Integer userId, @PathVariable("id") String id, @PathVariable("merchantCode") String merchantCode) {
        JSONObject params = new JSONObject();
        Map<String, Object> result = new HashMap<>(2);
        params.put("userId", userId + "");
        try {
            if (StringUtils.isEmpty(id) || "undefined".equals(id)) {
                QueryWrapper<MerchantChannelStatus> queryWrapper = new QueryWrapper<MerchantChannelStatus>().eq("merchantCode", merchantCode);
                MerchantChannelStatus one = mcsService.getOne(queryWrapper);
                one.setStatus(MerchantChannelStatus.AUDIT_STATUS_EXAMINING);
                one.setThirdStatus(MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING);
                mcsService.updateById(one);
                id = String.valueOf(one.getChannel());
            }

            userAppService.merchantAudit(params, id);

            result.put("code", "1");
            result.put("msg", "发起进件成功，等待审核中！");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "0");
            result.put("msg", e.getMessage());
            return result;
        }
    }

    /**
     * 手动后台发起进件
     */
    @PostMapping(value = "/reAuditYs/{merchantCode}")
    @ResponseBody
    public Map<String, Object> reAuditYs(@PathVariable("merchantCode") String merchantCode) {
        MerchantChannelStatus mcs = mcsService.getByMerchantCode(merchantCode, 4);
        UserApp ua = new UserApp();
        ua.setMerchantCode(merchantCode);
        ua.setUserType("promoter");
        ua = userAppService.getOne(new QueryWrapper<>(ua));
        if (mcs == null) {
            mcs = new MerchantChannelStatus();
        } else {
            if (mcs.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_EXAMINING) && !mcs.getThirdStatus().equals(MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING)) {
                Map<String, Object> result = new HashMap<>(2);
                result.put("code", "0");
                result.put("msg", "该商户进件正在审核中");
                return result;
            }
        }

        mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_EXAMINING);
        mcs.setMerchantCode(merchantCode);
        mcs.setThirdStatus(MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING);
        mcs.setAuthorizationStatus(MerchantChannelStatus.AUTHORIZATION_STATUS_UNAUTHORIZED);
        mcs.setValid(0);

        if (mcs.getId() == null) {
            mcsMapper.insert(mcs);
        } else {
            mcsMapper.updateById(mcs);
        }

        Map<String, Object> result = new HashMap<>(2);
        try {
            JSONObject params = new JSONObject();
            params.put("userId", ua.getUserId() + "");
            ysAuditServiceV2.merchantAudit(ua.getUserId() + "", false);
            // userAppService.merchantAudit(params, "4");
            result.put("code", "1");
            result.put("msg", "发起进件成功, 稍后查看进件状态");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "0");
            result.put("msg", e.getMessage());
            return result;
        }
    }

    /**
     * 进件审核驳回
     */
    @PassToken
    @GetMapping(value = "/rejectAudit/{userId}")
    @ResponseBody
    public Map<String, Object> rejectAudit(@PathVariable("userId") Integer userId, String errMsg) {
        UserApp userApp = new UserApp().setUserId(userId.longValue()).setUserType("promoter");
        userApp = userAppService.queryUserApp(userApp);

        Map<String, Object> result = new HashMap<>(2);
        try {
            mcsService.rejectAudit(userApp.getMerchantCode(), errMsg);
            result.put("code", "1");
            result.put("msg", "处理成功");
        } catch (Exception e) {
            result.put("code", "0");
            result.put("msg", e.getMessage());
        }

        return result;
    }

    /**
     * 进件审核驳回
     */
    @PostMapping(value = "/canAudit")
    @ResponseBody
    public Map<String, Object> rejectAudit(@RequestParam Integer userId) {
        LambdaQueryWrapper<CommonRemark> qWrapper = new LambdaQueryWrapper<>();
        qWrapper.eq(CommonRemark::getCode, "CAN_AUDIT")
                .eq(CommonRemark::getUserId, userId);

        remarkService.remove(qWrapper);

        Map<String, Object> result = new HashMap<>(2);
        result.put("code", "1");
        result.put("msg", "处理成功");
        return result;
    }

    /**
     * 进件审核驳回
     */
    @GetMapping(value = "/rejectAudit2/{userId}")
    @ResponseBody
    public Map<String, Object> rejectAudit2(@PathVariable("userId") Integer userId, String errMsg) {
        UserApp userApp = new UserApp().setUserId(userId.longValue()).setUserType("promoter");
        userApp = userAppService.queryUserApp(userApp);

        Map<String, Object> result = new HashMap<>(2);
        try {
            CommonRemark commonRemark = new CommonRemark()
                    .setRemark("-1")
                    .setUserId(userId)
                    .setCode("CAN_AUDIT");
            remarkService.save(commonRemark);
            mcsService.rejectAudit(userApp.getMerchantCode(), errMsg);
            result.put("code", "1");
            result.put("msg", "处理成功");
        } catch (Exception e) {
            result.put("code", "0");
            result.put("msg", e.getMessage());
        }

        return result;
    }

    /**
     * 进件审核驳回
     */
    @GetMapping(value = "/rejectPluginAudit/{userId}")
    @ResponseBody
    public Map<String, Object> rejectPluginAudit(@PathVariable("userId") Integer userId, String errMsg) {
        UserApp userApp = new UserApp().setUserId(userId.longValue());
        userApp = userAppService.queryUserApp(userApp);

        Map<String, Object> result = new HashMap<>(2);
        try {
            merchantPluginService.refuse(userApp.getUserId().toString(), errMsg);
            result.put("code", "1");
            result.put("msg", "处理成功");
        } catch (Exception e) {
            result.put("code", "0");
            result.put("msg", e.getMessage());
            return result;
        }


        return result;
    }

    /**
     * 手动后台批量发起进件
     */
    @GetMapping(value = "/batchMerchantIncom")
    @ResponseBody
    public Map<String, Object> manualMerchantIncom() {
        Map<String, Object> result = new HashMap<>();
        merchantStoreService.manualMerchantIncom();
        result.put("code", "1");
        result.put("msg", "进件任务执行中...");
        return result;
    }

    /**
     * 插件审核
     */
    @PassToken
    @GetMapping(value = "/audit/{userId}")
    @ResponseBody
    public Map<String, Object> audit(@PathVariable("userId") Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            merchantPluginService.audit(String.valueOf(userId));
            result.put("code", "200");
            result.put("msg", "进件任务执行中...");
        } catch (Exception e) {
            result.put("code", "0");
            result.put("msg", e.getMessage());
        }

        return result;
    }

    /**
     * @param file:
     * @return cn.pluss.platform.api.Result<?>
     * @description:批量导入d0excel开通文件
     * @date: 2021/8/4 11:46
     */
    @RequestMapping(value = "/exportD0Excel")
    @ResponseBody
    public Result<?> exportD0Excel(@RequestParam("file") MultipartFile file) {
        return merchantStoreService.exportD0Excel(file);
    }


    @GetMapping("/dowloadD0QuicklyExcel")
    @ResponseBody
    public void dowloadD0QuicklyExcel(HttpServletResponse response, String startTime, String endTime) throws IOException {
        if (StringUtils.isEmpty(startTime)) {
            return;
        }
        if (StringUtils.isEmpty(endTime)) {
            return;
        }
        String suffix = ".zip";
        QueryWrapper<MerchantChannelStatus> queryWrapper = new QueryWrapper<MerchantChannelStatus>()
                .in("status", MerchantChannelStatus.AUDIT_STATUS_QUICK_CASH, MerchantChannelStatus.AUDIT_STATUS_EXAMINING)
                .eq("channel", 4)
                .ne("thirdStatus", MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING)
                .between("createTime", startTime, endTime);
        List<MerchantChannelStatus> list = mcsService.list(queryWrapper);
        if (list.isEmpty()) {
            return;
        }
        String tempName = DateUtils.formatDateDefault(DateUtils.parse(startTime, "yyyy-MM-dd HH:mm:ss"), "yyyyMMddHHmm") + "快付审核";
        String uploadTempPath = "/home/syb/resources/d0/temp";
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os.startsWith("win") || os.startsWith("Win")) {
            uploadTempPath = "E:/crystal/temp";// 测试 // windows目录
        }
        String tempPath = uploadTempPath + File.separator + tempName;
        File file = new File(tempPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        for (MerchantChannelStatus channelStatus : list) {
            MerchantBaseInfo merchant = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(channelStatus.getMerchantCode());
            if (merchant != null) {
                File f1 = new File(tempPath + File.separator + merchant.getAlias());
                if (!f1.exists()) {
                    f1.mkdirs();
                }
                QueryWrapper<MerchantImage> imageQuery = new QueryWrapper<MerchantImage>().eq("merchantCode", merchant.getMerchantCode())
                        .in("photoType", "06", "08", "09");
                List<MerchantImage> imageList = merchantImageService.list(imageQuery);
                String savePath = tempPath + File.separator + merchant.getAlias();
                if (!imageList.isEmpty()) {
                    for (MerchantImage image : imageList) {
                        try {
                            String fileName = UUID.randomUUID().toString() + ".jpg";
                            FileUtil.downloadFile(image.getPicUrl(), savePath + File.separator + fileName);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        FileOutputStream fos1 = new FileOutputStream(new File(uploadTempPath + File.separator + tempName + suffix));
        ZipUtil.toZip(tempPath, fos1, true);
        FileUtil.downLoad(response, tempName + suffix, tempPath + suffix);
        FileUtil.deleteDir(new File(uploadTempPath));
    }


    /**
     * 关闭通道支付权限
     * @param channelId     通道id
     * @param merchantCode  商编
     * @return
     */
    @PostMapping("/banChannelValid")
    public Result<String> banChannelValid(int channelId, String merchantCode, String remark) {
        LambdaQueryWrapper<MerchantChannelStatus> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantChannelStatus::getChannel, channelId);
        qWrapper.eq(MerchantChannelStatus::getMerchantCode, merchantCode);

        MerchantChannelStatus mcs = mcsService.getOne(qWrapper);

        LambdaUpdateWrapper<MerchantChannelStatus> uWrapper = Wrappers.lambdaUpdate();
        uWrapper.eq(MerchantChannelStatus::getId, mcs.getId());
        uWrapper.set(MerchantChannelStatus::getValid, MerchantChannelStatus.VALID_STATUS_BAN)
                .set(MerchantChannelStatus::getUpdateTime, mcs.getUpdateTime())
                .set(MerchantChannelStatus::getRemark, remark);
        mcsService.update(uWrapper);

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

    /**
     * 关闭通道支付权限
     * @param channelId     通道id
     * @param merchantCode  商编
     * @return
     */
    @PostMapping("/openChannelValid")
    public Result<String> openChannelValid(int channelId, String merchantCode) {
        LambdaQueryWrapper<MerchantChannelStatus> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantChannelStatus::getChannel, channelId);
        qWrapper.eq(MerchantChannelStatus::getMerchantCode, merchantCode);

        MerchantChannelStatus mcs = mcsService.getOne(qWrapper);

        LambdaUpdateWrapper<MerchantChannelStatus> uWrapper = Wrappers.lambdaUpdate();
        uWrapper.eq(MerchantChannelStatus::getId, mcs.getId());
        uWrapper.set(MerchantChannelStatus::getValid, MerchantChannelStatus.VALID_STATUS_NORMAL)
                .set(MerchantChannelStatus::getUpdateTime, mcs.getUpdateTime());
        mcsService.update(uWrapper);

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


