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

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.direct.SysDictBean;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.logic.OperatorLogic;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.AdminModuleService;
import com.zfire.mall.manager.plus.service.KingDeeSyncTaskService;
import com.zfire.mall.manager.plus.service.SysDictService;
import com.zfire.mall.manager.plus.service.TaxConfigService;
import com.zfire.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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;


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

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    TaxConfigService taxConfigService;
    @Autowired
    KingDeeSyncTaskService kingDeeSyncTaskService;
    @Autowired
    AdminModuleService adminModuleService;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    WalletLogic walletLogic;
    @Autowired
    OperatorLogic operatorLogic;

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


    @GetMapping("/file/get")
    @ApiOperation(value = "获取附件地址")
    public ResponseHelper<String> getFile(
            @ApiParam(required = true, value = "附件key") @RequestParam(required = true) String key,
            HttpServletResponse response
    ) throws IOException, RemoteServiceException {
        String file = commonLogic.getFile(key, response);
        return ResponseHelper.success(file);
    }

    @GetMapping("/file/getStream")
    @ApiOperation(value = "直接下载文件")
    public void getFileStream(
            @ApiParam(required = true, value = "附件key") @RequestParam(required = true) String key,
            @ApiParam(required = true, value = "下载名称") @RequestParam(required = true) String fileName,
            HttpServletResponse response
    ) throws IOException, RemoteServiceException {
        String fileUrl = commonLogic.getFile(key, response);
        InputStream inputStream = commonLogic.getFileInputStreamByUrl(fileUrl);
        CommonUtils.downloadFile(inputStream,fileName,response);
    }


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


    @GetMapping("/dict/list")
    @ApiOperation("字典")
    public ResponseHelper<List<SysDict>> sysDictList(
            @ApiParam(value = "类型",required = false) @RequestParam(required = false) String sysDictEnum
    ) throws RemoteServiceException {
        List<SysDict> sysDicts = commonLogic.getSysDictList(sysDictEnum);
        return ResponseHelper.success(sysDicts);
    }

    @PostMapping("/dict/add")
    @ApiOperation("添加字典")
    public ResponseHelper updateSysDict (
            @RequestBody SysDict sysDict
    ){
        commonLogic.addSysDict(sysDict);
        return ResponseHelper.success();
    }

    @PostMapping("/dict/update")
    @ApiOperation("修改字典")
    public ResponseHelper updateSysDict(
            @RequestBody List<SysDict> sysDicts
    ){
        commonLogic.updateSysDict(sysDicts);
//        sysDictService.updateBatchById(sysDicts);
        return ResponseHelper.success();
    }

    @PostMapping("/dict/del")
    @ApiOperation("删除字典")
    public ResponseHelper updateSysDict(
            @RequestParam String id
    ){
        sysDictService.removeById(id);
        return ResponseHelper.success();
    }



    @PostMapping("/tax/config")
    @ApiOperation("税率配置")
    public ResponseHelper taxConfig(
            @ApiParam(value = "税率配置",required = true)  @RequestBody TaxConfig taxConfig
    ) throws RemoteServiceException {
        taxConfigService.removeById("1");
        taxConfig.setId("1");
        taxConfigService.save(taxConfig);
        return ResponseHelper.success();
    }

    @PostMapping("/tax/get")
    @ApiOperation("获取税率配置")
    public ResponseHelper getTaxConfig() throws RemoteServiceException {
        List<TaxConfig> list = taxConfigService.list();
        return ResponseHelper.success(list.get(0));
    }

    @GetMapping("/interface/list")
    @ApiOperation("接口状态列表")
    public ResponseHelper<IPage<KingDeeSyncTask>> taxConfig(
            @ApiParam(value = "接口名称",required = false) @RequestParam(required = false)  String name,
            @ApiParam(value = "接口状态 0=未同步 1=已同步 2=同步失败",required = false) @RequestParam(required = false)  String status,
            @ApiParam(value = "pageNum",required = false) @RequestParam(required = false)  Integer pageNum,
            @ApiParam(value = "pageSize",required = false) @RequestParam(required = false)  Integer pageSize
    ) throws RemoteServiceException {
        IPage<KingDeeSyncTask> list = kingDeeSyncTaskService.lambdaQuery()
                .like(StringUtils.isNotEmpty(name), KingDeeSyncTask::getName, name)
                .eq(StringUtils.isNotEmpty(status), KingDeeSyncTask::getStatus, status)
                .orderByDesc(KingDeeSyncTask::getCreateTime)
                .page(new Page<>(pageNum,pageSize));
        return ResponseHelper.success(list);
    }

    @PostMapping("/initAdminModule")
    @ApiOperation("initAdminModule")
    public ResponseHelper initAdminModule(){
        List<AdminModule> list = adminModuleService.lambdaQuery().eq(AdminModule::getType, 2).list();
        for(AdminModule adminModule : list){
//            this.supply("新增",adminModule.getModuleId(),"add",adminModule.getLevel()).insert();
//            this.supply("编辑",adminModule.getModuleId(),"edit",adminModule.getLevel()).insert();
//            this.supply("删除",adminModule.getModuleId(),"del",adminModule.getLevel()).insert();
//            this.supply("审核",adminModule.getModuleId(),"examine",adminModule.getLevel()).insert();
//            this.supply("打印",adminModule.getModuleId(),"print",adminModule.getLevel()).insert();
//            this.supply("申请/撤回",adminModule.getModuleId(),"apply",adminModule.getLevel()).insert();
//            this.supply("修改单据日期",adminModule.getModuleId(),"date",adminModule.getLevel()).insert();
            this.supply("导入",adminModule.getModuleId(),"import",adminModule.getLevel()).insert();
        }
        return ResponseHelper.success();
    }


    private AdminModule supply(String moduleName,String parentId,String code,Integer level){
        AdminModule bean = new AdminModule();
        bean.setModuleName(moduleName);
        bean.setType(3);
        bean.setCode(code);
        bean.setLevel(level+1);
        bean.setUrl("");
        bean.setParentId(parentId);
        bean.setSortNum(0);
        bean.setCreateTime(new Date());
        return bean;
    }


//    @PostMapping("/test")
//    public void test() throws InterruptedException {
//        commonLogic.test();
//    }


    @RequestMapping(value = "/dict/listDict",method = {RequestMethod.GET,RequestMethod.POST})
    //@GetMapping("/dict/listDict")
    @ApiOperation("下拉框查询")
    public ResponseHelper<List<SysDictBean>> sysDictBeanList(
            @ApiParam(value = "类型",required = true) @RequestParam(required = true) String code
    ) throws RemoteServiceException {
        List<SysDictBean> sysDicts = commonLogic.sysDictBeanList(code);
        return ResponseHelper.success(sysDicts);
    }

    @GetMapping("/log/list")
    @ApiOperation("操作日志列表")
    public ResponseHelper<IPage<OperatorLog>> operatorList(
            @RequestParam(required = true) String objId,
            @RequestParam(required = true) Integer pageNum,
            @RequestParam(required = true) Integer pageSize
    ){
        IPage<OperatorLog> operatorLogIPage = operatorLogic.LogList(objId, pageNum, pageSize);
        return ResponseHelper.success(operatorLogIPage);
    }

    @PostMapping("/region")
    @ApiOperation("高德省市区街道")
    public ResponseHelper<List<LbsAmap>> regionList(
            @ApiParam(value = "父级id，为空则返回省", required = false) @RequestParam(required = false) List<String> parentLbsId
    ) {
        List<LbsAmap> lbsAmaps = commonLogic.regionList(parentLbsId);
        return ResponseHelper.success(lbsAmaps);
    }

}
