package com.artfess.portal.controller;

import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.controller.BaseController;
import com.artfess.base.id.IdGenerator;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.FileUtil;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.base.util.ZipUtil;
import com.artfess.base.util.time.DateFormatUtil;
import com.artfess.sysConfig.persistence.manager.SysIdentityManager;
import com.artfess.sysConfig.persistence.model.SysIdentity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 描述：单据号规则 控制器类
 * @author dengyg
 * @company 阿特菲斯信息技术有限公司
 * @email dengyg@jee-soft.cn
 * @date 2018-06-06 14:20
 * </pre>
 */
@RestController
@RequestMapping("/sys/identity/v1")
@Api(tags = "单据号规则")
@ApiGroup(group = {ApiGroupConsts.GROUP_SYSTEM})
public class SysIdentityController extends BaseController<SysIdentityManager, SysIdentity> {
    @Resource
    SysIdentityManager identityManager;
    @Resource
    protected IdGenerator idGenerator;

    @RequestMapping(value = "listJson", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "单据号规则生成列表(分页条件查询)数据", httpMethod = "POST", notes = "单据号规则生成列表(分页条件查询)数据")
    public PageList<SysIdentity> listJson(HttpServletRequest request, HttpServletResponse reponse, @ApiParam(name = "queryFilter", value = "通用查询对象") @RequestBody QueryFilter<SysIdentity> queryFilter) throws Exception {
        return identityManager.query(queryFilter);
    }

    @RequestMapping(value = "getAll", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取所有单据号规则", httpMethod = "POST", notes = "单据号规则生成列表(分页条件查询)数据")
    public List<SysIdentity> getAll() throws Exception {
        return identityManager.list();
    }

    @RequestMapping(value = "getById", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "根据id获取单据号规则", httpMethod = "GET", notes = "根据id获取单据号规则")
    public Object getById(HttpServletRequest request, HttpServletResponse response, @ApiParam(name = "id", value = "单据号规则定义Id", required = true) @RequestParam String id) throws Exception {
        SysIdentity identity = identityManager.get(id);
        return identity;
    }

    @RequestMapping(value = "getJson", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "单据号规则明细页面", httpMethod = "GET", notes = "单据号规则明细页面")
    public Object get(HttpServletRequest request, HttpServletResponse response, @ApiParam(name = "id", value = "单据号规则定义Id", required = true) @RequestParam String id) throws Exception {
        SysIdentity identity = null;
        if (StringUtil.isNotEmpty(id)) {
            identity = identityManager.get(id);
        }
        return identity;
    }

    @RequestMapping(value = "save", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "保存单据号规则", httpMethod = "POST", notes = "保存单据号规则")
    public Object save(@ApiParam(name = "identity", value = "单据号规则定义", required = true) @RequestBody SysIdentity identity) throws Exception {
        String resultMsg = null;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", identity.getId());
        params.put("alias", identity.getAlias());
        boolean rtn = identityManager.isAliasExisted(params);
        if (rtn) {
            return new CommonResult<String>(false, "单据号规则别名已经存在", null);
        }
        try {
            if (StringUtil.isEmpty(identity.getId())) {
                identity.setId(idGenerator.getSuid());
                identityManager.create(identity);
                resultMsg = "添加单据号规则生成成功";
            } else {
                identityManager.update(identity);
                resultMsg = "更新单据号规则生成成功";
            }
            return new CommonResult<String>(true, resultMsg, null);
        } catch (Exception e) {
            return new CommonResult<String>(false, resultMsg, null);
        }
    }

    @RequestMapping(value = "remove", method = RequestMethod.DELETE, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "批量删除单据号规则", httpMethod = "DELETE", notes = "批量删除单据号规则")
    public Object remove(@ApiParam(name = "ids", value = "单据号规则定义Ids", required = true) @RequestParam String ids) throws Exception {
        try {
            String[] aryIds = StringUtil.getStringAryByStr(ids);
            identityManager.removeByIds(Arrays.asList(aryIds));
            return new CommonResult<String>(true, "删除成功", null);
        } catch (Exception e) {
            return new CommonResult<String>(false, "删除失败", null);
        }
    }

    @RequestMapping(value = "preview", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "单据号规则预览", httpMethod = "GET", notes = "单据号规则预览")
    public PageList<SysIdentity> preview(@ApiParam(name = "alias", value = "单据号规则别名", required = true) @RequestParam String alias) throws Exception {
        List<SysIdentity> identities = identityManager.getPreviewIden(alias);
        return new PageList<SysIdentity>(identities);
    }

    @RequestMapping(value = "getNextIdByAlias", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "获取下一个单据号规则", httpMethod = "GET", notes = "获取下一个单据号规则")
    public CommonResult<String> getNextIdByAlias(@ApiParam(name = "alias", value = "单据号规则别名", required = true) @RequestParam String alias) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("id", null);
        params.put("alias", alias);
        if (identityManager.isAliasExisted(params)) {
            String nextId = identityManager.nextId(alias);
            return new CommonResult<String>(true, "获取单据号规则成功！", nextId);
        }
        return new CommonResult<String>(false, "获取单据号规则失败！");
    }

    @RequestMapping(value = "export", method = RequestMethod.GET, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "导出数据", httpMethod = "GET", notes = "导出数据")
    public void export(HttpServletResponse response, HttpServletRequest request,
                       @ApiParam(name = "ids", value = "ids", required = true) @RequestParam String ids) throws Exception {
        String[] idList = ids.split(",");
        String fileName = "identity_" + DateFormatUtil.format(LocalDateTime.now(), "yyyy_MMdd_HHmm");
        String json = identityManager.export(idList);
        HttpUtil.downLoadFile(request, response, json, "identity.json", fileName);
    }

    @RequestMapping(value = "import", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "导入单据号规则", httpMethod = "POST", notes = "导入单据号规则")
    public CommonResult<String> importIdentity(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile file = request.getFile("file");
        String unZipFilePath = "";
        try {
            String rootRealPath = (FileUtil.getIoTmpdir() + "/attachFiles/unZip/").replace("/", File.separator);
            FileUtil.createFolder(rootRealPath, true);
            String name = file.getOriginalFilename();
            String fileDir = StringUtil.substringBeforeLast(name, ".");
            ZipUtil.unZipFile(file, rootRealPath); // 解压文件
            unZipFilePath = rootRealPath + File.separator + fileDir; // 解压后文件的真正路径
            identityManager.importFile(unZipFilePath);
            return new CommonResult<>(true, "导入成功");
        } catch (Exception e) {
            return new CommonResult<>(false, "导入失败：" + e.getMessage());
        } finally {
            if (StringUtil.isNotEmpty(unZipFilePath)) {
                File zipFile = new File(unZipFilePath);
                if (zipFile.exists()) {
                    zipFile.delete();
                }
            }
        }
    }
}
