package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysConfigService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysDictionaryService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysFileService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysOrderNoRuleService;
import cn.estsh.i3plus.core.apiservice.util.ExcelUtil;
import cn.estsh.i3plus.core.apiservice.util.FileUtil;
import cn.estsh.i3plus.core.apiservice.util.ZipUtil;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.CommonConstWords;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.BaseConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SysDictionary;
import cn.estsh.i3plus.pojo.platform.bean.SysFile;
import cn.estsh.i3plus.pojo.platform.bean.SysOrderNoRule;
import cn.estsh.i3plus.pojo.platform.bean.SysUserInfo;
import cn.estsh.i3plus.pojo.platform.platbean.SysLogOperate;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.fastdfs.FastDFSClient;
import cn.estsh.impp.framework.boot.fastdfs.FastDFSFile;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import com.netflix.discovery.converters.Auto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description :系统单号规则管理服务
 * @Reference :
 * @Author : yunhao
 * @CreateDate : 2018-11-21 18:20
 * @Modify:
 **/
@RestController
@Api(description = "系统单号规则管理服务")
@RequestMapping(PlatformConstWords.BASE_URL + "/sys-order-no-rule")
public class SysOrderNoRuleController extends CoreBaseController {

    @Autowired
    private ISysOrderNoRuleService sysOrderNoRuleService;

    @Autowired
    private ISysDictionaryService sysDictionaryService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private FastDFSClient dfsClient;

    @PostMapping(value = "/insert")
    @ApiOperation(value = "新增单号规则")
    public ResultBean insertSysOrderNoRule(SysOrderNoRule sysOrderNoRule){
        try {
            // 添加校验
            validatorSysOrderNoRule(sysOrderNoRule);

            sysOrderNoRule.setOrderNoRuleStatus(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
            sysOrderNoRule.setSerialNo(CommonEnumUtil.PARENT.DEFAULT.getValue());

            sysOrderNoRuleService.insertSysOrderNoRule(sysOrderNoRule);
            return  ResultBean.success("操作成功").setResultObject(sysOrderNoRule).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改单号规则")
    public ResultBean updateSysOrderNoRule(SysOrderNoRule sysOrderNoRule){
        try {
            ValidatorBean.beginValid(sysOrderNoRule)
                    .notNull("id",sysOrderNoRule.getId())
                    .notNull("name",sysOrderNoRule.getName())
                    .notNull("orderNoRuleCode",sysOrderNoRule.getOrderNoRuleCode())
                    .notNull("orderNoRule",sysOrderNoRule.getOrderNoRule())
                    .checkNotZero("serialNoSeed",sysOrderNoRule.getSerialNoSeed())
                    .checkNotZero("serialNoIncrement",sysOrderNoRule.getSerialNoIncrement())
                    .checkNotZero("serialNoLength",sysOrderNoRule.getSerialNoLength())
                    .checkNotZero("isCycle",sysOrderNoRule.getIsCycle());

            sysOrderNoRuleService.updateSysOrderNoRule(sysOrderNoRule);
            return  ResultBean.success("操作成功").setResultObject(sysOrderNoRule).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "根据id获取编号规则")
    public ResultBean getSysOrderNoRuleById(@PathVariable("id") String idStr){
        try {
            ValidatorBean.checkNotNull(idStr,"id不能为空");

            SysOrderNoRule sysOrderNoRule = sysOrderNoRuleService.getSysOrderNoRuleById(Long.parseLong(idStr));
            if (sysOrderNoRule != null) {
                return  ResultBean.success("操作成功").setResultObject(sysOrderNoRule).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
            }else {
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/delete/{id}")
    @ApiOperation(value = "根据id删除单号规则")
    public ResultBean deleteSysOrderNoRuleById(@PathVariable("id") String idStr){
        try {
            ValidatorBean.checkNotNull(idStr,"id不能为空");

            sysOrderNoRuleService.deleteSysOrderNoRuleById(Long.parseLong(idStr));
            return  ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/query")
    @ApiOperation(value = "单号规则复杂查询，分页，排序")
    public ResultBean querySysOrderNoRuleByPager(SysOrderNoRule sysOrderNoRule, Pager pager){
        try {
            ListPager sysOrderNoRuleList = sysOrderNoRuleService.querySysOrderNoRuleByPager(sysOrderNoRule, pager);
            return  ResultBean.success("操作成功").setListPager(sysOrderNoRuleList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/status/{id}/{status}")
    @ApiOperation(value = "根据id修改规则状态")
    public ResultBean updateSysOrderNoRuleStatusById(@PathVariable("id") String id,@PathVariable("status") Integer status){
        try {
            ValidatorBean.checkNotNull(id,"code不能为空");
            ValidatorBean.checkNotZero(status,"code不能为空");

            sysOrderNoRuleService.updateSysOrderNoRuleCodeStatusById(Long.parseLong(id),status);
            return  ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/batch-delete")
    @ApiOperation(value = "批量删除单号规则")
    public ResultBean deleteSysOrderNoRuleByIds(String[] idsStr){
        try {
            if(idsStr.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }

            sysOrderNoRuleService.deleteSysOrderNoRuleByIds(StringTool.getArrayLong(idsStr));
            return  ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/batch-status")
    @ApiOperation(value = "根据id批量修改规则状态")
    public ResultBean updateSysOrderNoRuleStatusByIds(String[] idsStr,Integer status){
        try {
            if(idsStr.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }
            ValidatorBean.checkIsNumber(status,"状态不能为空！");

            sysOrderNoRuleService.updateSysOrderNoRuleByIds(StringTool.getArrayLong(idsStr),status);
            return  ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/export")
    @ApiOperation(value = "导出操作日志")
    public ResultBean exportSysOrderNoRule(SysOrderNoRule sysOrderNoRule, String[] colName, int pageSize, boolean isZip) {
        ListPager listPager;
        List result = new ArrayList();
        File zipFile = null;
        File excelDir = null;
        File excelFile;
        try {
            Pager pager = new Pager();
            pager.setCurrentPage(1);
            // 判断是否超过excel最大导出数量设定值
            int maxPageSize = Integer.parseInt(sysConfigService.getSysConfigByCode(PlatformConstWords.EXCEL_EXPORT_MAX_ROW).getConfigValue());
            if (pageSize == 0 || pageSize >= maxPageSize) {
                pager.setPageSize(maxPageSize);
            } else {
                pager.setPageSize(pageSize);
            }

            // 数据校验
            if(colName==null || colName.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.IMPP.getCode())
                        .setErrorCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode())
                        .setErrorDetail("导出列不能为空")
                        .build();
            }

            excelDir = new File(System.getProperty("java.io.tmpdir") + File.separator + new Date().getTime());
            excelDir.mkdir();
            do {
                listPager = sysOrderNoRuleService.querySysOrderNoRuleByPager(sysOrderNoRule, pager);
                pager = listPager.getObjectPager();

                // 将excel导出至临时文件夹并上传
                excelFile = new File(excelDir + File.separator + SysOrderNoRule.class.getSimpleName() + pager.getCurrentPage() + ".xls");
                excelFile.createNewFile();

                ExcelUtil.exportData(excelFile, listPager.getObjectList(), SysOrderNoRule.class, colName);
                result.add(sysFileService.uploadFile(excelFile));

                pager.setCurrentPage(pager.getCurrentPage() + 1);
            } while (pager.getCurrentPage() <= pager.getTotalPages());

            // 将所有excel文件打包
            if(isZip){
                zipFile = ZipUtil.zipFile(null, excelDir);
                result.add(sysFileService.uploadFile(zipFile));
                ExcelUtil.sendStationLetter(result,getSessionUser().getUser().getId());
                return ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(result);
            } else {
                return ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(result);
            }
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        } finally {
            // 清理临时文件文件
            if (zipFile != null) {
                FileUtil.deletefile(zipFile.getPath());
            }
            if(excelDir != null){
                FileUtil.deletefile(excelDir.getPath());
            }
        }
    }

    @PostMapping(value = "/import")
    @ApiOperation(value = "导入单号规则")
    public ResultBean importSysOrderNoRule(@RequestParam("file") MultipartFile file){
        try {
            List<SysOrderNoRule> sysOrderNoRuleList = ExcelUtil.importData(file.getOriginalFilename(),file.getInputStream(),SysOrderNoRule.class);
            // 初始化数据
            for (SysOrderNoRule sysOrderNoRule: sysOrderNoRuleList) {
                sysOrderNoRule.setOrderNoRuleStatus(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                sysOrderNoRule.setSerialNo(CommonEnumUtil.PARENT.DEFAULT.getValue());
            }
            sysOrderNoRuleService.insertSysOrderNoRuleList(sysOrderNoRuleList);
            return  ResultBean.success("导入成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/down-template")
    @ApiOperation(value = "下载导入模板")
    public ResultBean downSysOrderNoRuleTemplate(){
        try {
            FastDFSFile fastDFSFile = new FastDFSFile(SysOrderNoRule.class.getSimpleName() + "ImportTemplate.xls",
                    ExcelUtil.importTemplate(SysOrderNoRule.class),"xls");

            String[] fileAbsolutePath = dfsClient.upload(fastDFSFile);

            // 保证系统文件表中
            String filePath = dfsClient.getHostUi() + "/" + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
            SysDictionary dictionary = sysDictionaryService.getSysDictionaryByParentCodeAndCode(
                    BaseConstWords.DICTIONARY_FILE_TYPE,fastDFSFile.getExt());

            SysFile sysFile = new SysFile();
            sysFile.setDfsGroupName(fileAbsolutePath[0]);
            sysFile.setDfsFileName(fileAbsolutePath[1]);
            sysFile.setFileSize(fastDFSFile.getContent().length);
            sysFile.setFilePath(filePath);
            sysFile.setFileOriginalName(fastDFSFile.getName());
            sysFile.setFileTypeId(dictionary.getId());
            sysFile.setFileTypeName(dictionary.getName());
            sysFile.setDownloadNum(0);
            sysFileService.insertSysFile(sysFile);

            return  ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(sysFile);
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping("/get-col")
    @ApiOperation(value = "获取单号规则字段")
    public ResultBean getSysOrderNoRuleColName(){
        try {
            return  ResultBean.success("导出成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultMap(ExcelUtil.getColName(SysOrderNoRule.class));
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    /**
     * 对象添加校验
     * @param sysOrderNoRule 校验对象
     * @throws NoSuchFieldException
     */
    private void validatorSysOrderNoRule(SysOrderNoRule sysOrderNoRule) throws NoSuchFieldException {
        ValidatorBean.beginValid(sysOrderNoRule)
                .notNull("name",sysOrderNoRule.getName())
                .notNull("orderNoRuleCode",sysOrderNoRule.getOrderNoRuleCode())
                .notNull("orderNoRule",sysOrderNoRule.getOrderNoRule())
                .checkNotZero("serialNoSeed",sysOrderNoRule.getSerialNoSeed())
                .checkNotZero("serialNoIncrement",sysOrderNoRule.getSerialNoIncrement())
                .checkNotZero("serialNoLength",sysOrderNoRule.getSerialNoLength())
                .checkNotZero("isCycle",sysOrderNoRule.getIsCycle());
    }


    @GetMapping(value = "/get-order-no/{code}")
    @ApiOperation(value = "根据单号规则代码，生成单号")
    public ResultBean getOrderNo(@PathVariable("code") String code){
        try {
            ValidatorBean.checkNotNull(code,"code不能为空");

            SysOrderNoRule sysOrderNoRule = sysOrderNoRuleService.getSysOrderNoRuleCode(code);
            return  ResultBean.success("操作成功").setResultObject(sysOrderNoRule).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }
}
