package com.yunzhi.marketing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.entity.SysAdvancedConfig;
import com.yunzhi.marketing.entity.TaAdvancedController;
import com.yunzhi.marketing.entity.TaMiniapp;
import com.yunzhi.marketing.entity.TaWxPayConfig;
import com.yunzhi.marketing.service.ISysAdvancedConfigService;
import com.yunzhi.marketing.service.ITaAdvancedControllerService;
import com.yunzhi.marketing.service.ITaMiniappService;
import com.yunzhi.marketing.service.ITaWxPayConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
    * 高级配置基础表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2020-02-26
 */
@RestController
@RequestMapping("/api")
public class SysAdvancedConfigController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(SysAdvancedConfigController.class);

    @Autowired
    public ISysAdvancedConfigService iSysAdvancedConfigService;

    @Autowired
    public ITaWxPayConfigService taWxPayConfigService;

    @Autowired
    public ITaAdvancedControllerService taAdvancedControllerService;

    @Autowired
    public ITaMiniappService taMiniappService;
    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/sysAdvancedConfig",method= RequestMethod.GET)
    public ResponseBean sysAdvancedConfigList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                              @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<SysAdvancedConfig> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<SysAdvancedConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date");

            IPage<SysAdvancedConfig> result = iSysAdvancedConfigService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysAdvancedConfigList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param sysAdvancedConfig 实体对象
     * @return
     */
    @RequestMapping(value="/sysAdvancedConfig",method= RequestMethod.POST)
    public ResponseBean sysAdvancedConfigAdd(@RequestBody SysAdvancedConfig sysAdvancedConfig){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iSysAdvancedConfigService.save(sysAdvancedConfig)){
                responseBean.addSuccess(sysAdvancedConfig);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysAdvancedConfigAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/sysAdvancedConfig/{id}", method= RequestMethod.DELETE)
    public ResponseBean sysAdvancedConfigDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iSysAdvancedConfigService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysAdvancedConfigDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param sysAdvancedConfig 实体对象
     * @return
     */
    @RequestMapping(value="/sysAdvancedConfig/{id}",method= RequestMethod.PUT)
    public ResponseBean sysAdvancedConfigUpdate(@PathVariable Integer id,
                                        @RequestBody SysAdvancedConfig sysAdvancedConfig){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (iSysAdvancedConfigService.updateById(sysAdvancedConfig)){
                responseBean.addSuccess(sysAdvancedConfig);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysAdvancedConfigUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/sysAdvancedConfig/{id}",method= RequestMethod.GET)
    public ResponseBean sysAdvancedConfigGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iSysAdvancedConfigService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysAdvancedConfigDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param orgId  小程序的orgId
     */
    @RequestMapping(value="/center/sysAdvancedConfig/list",method= RequestMethod.GET)
    public ResponseBean sysAdvancedConfigList(@RequestParam Integer orgId){
        ResponseBean responseBean = new ResponseBean();
        try {
            Map<String,Object> map = new HashMap<>();
            List<SysAdvancedConfig> sysAdvancedConfigList = iSysAdvancedConfigService.getSysAdvancedConfigList(orgId);
            TaWxPayConfig taWxPayConfig = taWxPayConfigService.getOne(new QueryWrapper<TaWxPayConfig>().eq("org_id", orgId));
            map.put("list",sysAdvancedConfigList);
            map.put("taWxPayConfig",taWxPayConfig);
            responseBean.addSuccess(map);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("sysAdvancedConfigDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 修改高级配置
     * @param data
     * @return
     */
    @PostMapping(value = "/center/sysAdvancedConfig/save")
    public ResponseBean saveAdvancedConfig(@RequestBody Map<String, Object> data) {
        Integer orgId = (Integer) data.get("orgId");
        List<Integer> advancedConfigIds = (List<Integer>) data.get("menus");
        Map<String,Object> wxPayData = (Map<String, Object>) data.get("wxPayData");

        try {
            if (advancedConfigIds.size() > 0){
                //插入高级控制表先删除后添加
                taAdvancedControllerService.remove(new QueryWrapper<TaAdvancedController>().eq("org_id",orgId));
                advancedConfigIds.forEach(e -> {
                    TaAdvancedController taAdvancedController = new TaAdvancedController();
                    taAdvancedController.setAdvancedConfigId(e);
                    taAdvancedController.setCreateDate(LocalDateTime.now());
                    taAdvancedController.setOrgId(orgId);
                    taAdvancedControllerService.save(taAdvancedController);
                });
            }
            if (wxPayData.size() > 0){
                TaMiniapp taMiniapp = taMiniappService.getOne(new QueryWrapper<TaMiniapp>().eq("org_id", orgId));
                if (!taMiniapp.getMiniappId().equals(wxPayData.get("appid"))){
                    return ResponseBean.error("appid不一致", ResponseBean.ERROR_UNAVAILABLE);
                }
                //维护支付信息先删除后添加
                taWxPayConfigService.remove(new QueryWrapper<TaWxPayConfig>().eq("org_id",orgId));
                TaWxPayConfig taWxPayConfig = new TaWxPayConfig();
                taWxPayConfig.setApiPath((String) wxPayData.get("apiPath"));
                taWxPayConfig.setAppid((String) wxPayData.get("appid"));
                taWxPayConfig.setMchId((String) wxPayData.get("mchId"));
                taWxPayConfig.setMchKey((String) wxPayData.get("mchKey"));
                taWxPayConfig.setOrgId(orgId);
                taWxPayConfig.setCreateDate(LocalDateTime.now());
                taWxPayConfigService.save(taWxPayConfig);
            }
        } catch (Exception e) {
            return ResponseBean.error(e.getMessage(), ResponseBean.ERROR_UNAVAILABLE);
        }

        return ResponseBean.success("ok");
    }
}
