package com.yeejoin.amos.boot.module.jcs.biz.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.core.framework.PersonIdentify;
import com.yeejoin.amos.boot.module.jcs.api.dto.OrganizationExportDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.OrganizationUserExportDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.Organization;
import com.yeejoin.amos.boot.module.jcs.api.service.OrganizationService;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "组织机构")
@RequestMapping(value = "/organization")
public class OrganizationController extends BaseController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private static String UTF8 = "UTF-8";
    private static String CONTENTDISPOSITION = "Content-Disposition";


    @PersonIdentify
    @GetMapping(value = "/getOrganizationInfo")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "四横八纵", notes = "四横八棕-组织机构")
    public ResponseModel getOrganizationInfo(@RequestParam(value = "pageNumber") int pageNumber,
                                             @RequestParam(value = "pageSize") int pageSize ) {
        ReginParams reginParam = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String bizOrgCode = null;
        if(null != reginParam) {
            bizOrgCode = reginParam.getPersonIdentity().getBizOrgCode();
            if (StringUtils.isEmpty(bizOrgCode)) {
                return CommonResponseUtil.success(null);
            }
        } else {
            return CommonResponseUtil.success(null);
        }
        Page<Map<String, Object>> mapPage = new Page<>(pageNumber, pageSize);
        return CommonResponseUtil.success(organizationService.getOrganizationInfo(mapPage, bizOrgCode));
    }

    @PersonIdentify
    @GetMapping(value = "/getOrganizationList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "四横八纵", notes = "四横八纵-组织列表")
    public ResponseModel getOrganizationList(@RequestParam(value = "pageNumber") int pageNumber,
                                             @RequestParam(value = "pageSize") int pageSize) {
        ReginParams reginParam = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String bizOrgCode = null;
        if (null != reginParam) {
            bizOrgCode = reginParam.getPersonIdentity().getBizOrgCode();
            if (StringUtils.isEmpty(bizOrgCode)) {
                return CommonResponseUtil.success(null);
            }
        } else {
            return CommonResponseUtil.success(null);
        }
        Page<Map<String, Object>> mapPage = new Page<>(pageNumber, pageSize);
        return CommonResponseUtil.success(organizationService.getOrganizationList(mapPage, bizOrgCode));
    }

    @PersonIdentify
    @GetMapping(value = "/export")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "四横八纵", notes = "四横八纵-组织机构导出")
    public void export(HttpServletResponse response) {
        String file_name = null;
        try {
            response.setCharacterEncoding(UTF8);
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader(CONTENTDISPOSITION, "attachment;filename=" + URLEncoder.encode("组织机构信息.xlsx", UTF8) );
            response.setHeader("Access-Control-Expose-Headers", CONTENTDISPOSITION);
            List<OrganizationExportDto> firstSheetVOS = new ArrayList<>();

            List<OrganizationUserExportDto> secondSheetVOS = new ArrayList<>();

            // 应急救援小组写入
            ExcelWriter writer = EasyExcelFactory.write(response.getOutputStream(), OrganizationExportDto.class).build();
            WriteSheet sheet = EasyExcelFactory.writerSheet(0, "应急救援小组").build();
            writer.write(firstSheetVOS, sheet);

            // 组员写入
            WriteSheet sheet2 = EasyExcelFactory.writerSheet(1, "组员").head(OrganizationUserExportDto.class).build();
            writer.write(secondSheetVOS, sheet2);

            // 关闭流
            writer.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @PersonIdentify
    @GetMapping(value = "/exportData")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "四横八纵", notes = "四横八纵-组织机构导出")
    public void exportData( HttpServletResponse response) {
        ReginParams reginParam = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String bizOrgCode = null;
        if(null != reginParam) {
            bizOrgCode = reginParam.getPersonIdentity().getBizOrgCode();
            if (StringUtils.isEmpty(bizOrgCode)) {
                return ;
            }
        }
        try {
            response.setCharacterEncoding(UTF8);
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader(CONTENTDISPOSITION, "attachment;filename=" + URLEncoder.encode("组织机构信息.xlsx", UTF8) );
            response.setHeader("Access-Control-Expose-Headers", CONTENTDISPOSITION);
            // 应急小组信息
            List<OrganizationExportDto> organizationList = organizationService.selectOrganization(bizOrgCode);
            // 应急小组人员信息
            List<OrganizationUserExportDto> organizationUserList = organizationService.selectOrganizationUserList(bizOrgCode);
            // 应急小组写入
            ExcelWriter writer = EasyExcelFactory.write(response.getOutputStream(), OrganizationExportDto.class).build();
            WriteSheet sheet = EasyExcelFactory.writerSheet(0, "应急救援小组").build();
            writer.write(organizationList, sheet);

            // 组员写入
            WriteSheet sheet2 = EasyExcelFactory.writerSheet(1, "组员").head(OrganizationUserExportDto.class).build();
            writer.write(organizationUserList, sheet2);

            // 关闭流
            writer.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @PersonIdentify
    @PostMapping(value = "/upload")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "四横八纵", notes = "四横八纵-组织机构导入")
    public ResponseModel upload(MultipartFile file) {
        ReginParams reginParam = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String bizOrgCode = null;
        if(null != reginParam) {
            bizOrgCode = reginParam.getPersonIdentity().getBizOrgCode();
            if (StringUtils.isEmpty(bizOrgCode)) {
                return CommonResponseUtil.failure();
            }
        }
        try {
            ExcelReader reader = EasyExcelFactory.read(file.getInputStream()).build();
            List<OrganizationExportDto> organizationList = ExcelUtil.readExcel(reader, OrganizationExportDto.class, 0);
            List<OrganizationUserExportDto> organizationUserList = ExcelUtil.readExcel(reader, OrganizationUserExportDto.class, 1);
            organizationService.saveOrganization(organizationList, organizationUserList, bizOrgCode);

        } catch (IOException e) {
            e.printStackTrace();
            throw  new BadRequest(e.getMessage());
        }

        return CommonResponseUtil.success();
    }


    /**
     * 新增应急小组信息
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增应急小组信息", notes = "新增应急小组信息")
    public ResponseModel<Organization> save(@RequestBody Organization organization) {
        return ResponseHelper.buildResponse(organizationService.saveOrganization(organization));
    }

    /**
     * 编辑应急小组信息
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/updateById", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "编辑应急小组信息", notes = "编辑应急小组信息")
    public ResponseModel<Organization> updateByIdDeviceServicing(@RequestBody Organization organization){
        return ResponseHelper.buildResponse(organizationService.updateModelById(organization));
    }

    /**
     * 上移下移
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/moveTeam")
    @ApiOperation(httpMethod = "GET", value = "上移下移", notes = "上移下移")
    public ResponseModel<Boolean> moveTeam(@RequestParam() String method, @RequestParam Long id){
        return ResponseHelper.buildResponse(organizationService.moveTeam(method, id));
    }

    @GetMapping(value = "/getList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取列表", notes = "获取列表")
    public ResponseModel<List<Organization>> getList() {
        return ResponseHelper.buildResponse(organizationService.getList());
    }

    @GetMapping(value = "/getDetailsById")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取详情", notes = "获取详情")
    public ResponseModel<Organization> getDetailsById(@RequestParam() Long id) {
        return ResponseHelper.buildResponse(organizationService.getDetailsById(id));
    }

    @GetMapping(value = "/deleteById")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "删除", notes = "根据id删除")
    public ResponseModel deleteById(@RequestParam() Long id) {
        return ResponseHelper.buildResponse(organizationService.deleteById(id));
    }
}
