package com.hzs.system.sys.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.DocumentMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.system.sys.SysApproval;
import com.hzs.common.domain.system.sys.SysUser;
import com.hzs.common.domain.system.sys.ext.SysApprovalExt;
import com.hzs.common.domain.system.sys.ext.SysApprovalItemExt;
import com.hzs.common.domain.system.sys.ext.SysApprovalSendExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
import com.hzs.system.sys.param.ApprovalParam;
import com.hzs.system.sys.param.ApprovalSaveParam;
import com.hzs.system.sys.service.*;
import com.hzs.system.sys.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Description: 签呈配置相关
 * Author: jiang chao
 * Time: 2022/9/15 15:08
 * Classname: SysApprovalController
 * PackageName: com.hzs.system.sys.controller.manage
 */
@Slf4j
@RestController
@RequestMapping("/manage/approval")
public class SysApprovalController extends BaseController {

    @Autowired
    private ISysApprovalService iSysApprovalService;
    @Autowired
    private ISysApprovalItemService iSysApprovalItemService;
    @Autowired
    private ISysApprovalSendService iSysApprovalSendService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysDeptService iSysDeptService;


    /**
     * 获取签呈配置列表
     *
     * @param param 查询参数
     * @return
     */
    @Log(module = EOperationModule.SIGN_CONFIG, business = EOperationBusiness.SIGN_CONFIG, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(ApprovalParam param) {
        startPage();
        return getDataTable(iSysApprovalService.approvalList(param, SecurityUtils.getPkCountry()));
    }

    /**
     * 导出
     *
     * @param response
     * @param param    查询参数
     */
    @Log(module = EOperationModule.SIGN_CONFIG, business = EOperationBusiness.SIGN_CONFIG, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ApprovalParam param) {
        List<ApprovalVO> resultList = iSysApprovalService.approvalList(param, SecurityUtils.getPkCountry());

        // 当查询有数据才进行处理
        if (resultList.size() > 0) {
            // 获取需要翻译的枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EApprovalBusiness.values());

            for (ApprovalVO approvalVO : resultList) {
                approvalVO.setApprovalBusinessVal(transactionMap.get(EnumsPrefixConstants.APPROVAL_BUSINESS + approvalVO.getApprovalBusiness()));
            }
        }
        ExcelUtil<ApprovalVO> util = new ExcelUtil<>(ApprovalVO.class);
        util.exportExcel(response, resultList, "签呈配置导出");
    }

    /**
     * 保存
     *
     * @param paramList 保存入参
     * @return
     */
    @Log(module = EOperationModule.SIGN_CONFIG, business = EOperationBusiness.SIGN_CONFIG, method = EOperationMethod.INSERT)
    @PostMapping
    public AjaxResult save(@RequestBody List<ApprovalSaveParam> paramList) {
        for (ApprovalSaveParam param : paramList) {
            if (null == param.getApprovalBusiness()
                    || CollectionUtils.isEmpty(param.getUserIdList())
                    || null == param.getEffectiveDate()) {
                return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
            }
            // 2024.05.20 去掉此校验
//            // 校验审批流程中有没有重复部门（2023.01.09 与产品沟通，同一审批流中同一部门只能出现一次）
//            if (CollectionUtil.isNotEmpty(iSysDeptService.queryRepeatDept(param.getUserIdList()))) {
//                // 审批流程中出现重复部门
//                return AjaxResult.error(TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_FLOW_REPEAT));
//            }

            // 业务类型处理业务大类
            param.setApprovalType(EApprovalType.getEnumByApprovalBusinessValue(param.getApprovalBusiness()).getValue());
            // 抄送用户去重
            param.setSendIdList(param.getSendIdList().stream().distinct().collect(Collectors.toList()));
        }
        iSysApprovalService.saveApproval(paramList, SecurityUtils.getUserId(), SecurityUtils.getPkCountry());
        return AjaxResult.success();
    }

    /**
     * 详情
     *
     * @param id 签呈ID
     * @return
     */
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id") Integer id) {
        ApprovalDetailVO detailVO = new ApprovalDetailVO();

        SysApproval sysApproval = iSysApprovalService.getById(id);
        if (null != sysApproval) {
            detailVO.setPkId(sysApproval.getPkId());
            detailVO.setApprovalBusiness(sysApproval.getApprovalBusiness());

            // 审批流程
            List<SysApprovalItemExt> itemList = iSysApprovalItemService.queryListByApproval(id);
            detailVO.setItemList(BeanUtil.copyToList(itemList, ApprovalDetailItemVO.class));

            // 审批抄送人
            List<SysApprovalSendExt> sendList = iSysApprovalSendService.queryListByApproval(Collections.singletonList(id));
            if (CollectionUtil.isNotEmpty(sendList)) {
                detailVO.setSendList(BeanUtil.copyToList(sendList, ApprovalDetailItemVO.class));
            }
        }

        return AjaxResult.success(detailVO);
    }

    /**
     * 删除
     *
     * @param id 签呈ID
     * @return
     */
    @Log(module = EOperationModule.SIGN_CONFIG, business = EOperationBusiness.SIGN_CONFIG, method = EOperationMethod.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Integer id) {
        iSysApprovalService.deleteApproval(id, SecurityUtils.getUserId(), SecurityUtils.getPkCountry());
        return AjaxResult.success();
    }

    /**
     * 是否存在签呈
     *
     * @param approvalBusinessList
     * @return
     */
    @GetMapping("/has-sign/{approvalBusinessList}")
    public AjaxResult hasSign(@PathVariable("approvalBusinessList") List<Integer> approvalBusinessList) {
        // 查询是否存在签呈
        List<SysApproval> sysApprovalList = iSysApprovalService.lastApproval(approvalBusinessList, SecurityUtils.getPkCountry());
        if (CollectionUtil.isNotEmpty(sysApprovalList)) {
            approval:
            for (Integer approvalBusiness : approvalBusinessList) {
                for (SysApproval sysApproval : sysApprovalList) {
                    if (sysApproval.getApprovalBusiness().equals(approvalBusiness)) {
                        // 存在则直接进行下次
                        continue approval;
                    }
                }
                EApprovalBusiness eApprovalBusiness = EApprovalBusiness.getEnumByValue(approvalBusiness);
                if (null != eApprovalBusiness) {
                    // %s 未配置签呈
                    return AjaxResult.error(TransactionUtils.getContent(DocumentMsgConstants.SIGN_NOT_CONFIG, eApprovalBusiness.getLabel()));
                }
                // 签呈业务类型错误
                return AjaxResult.error(TransactionUtils.getContent(DocumentMsgConstants.SIGN_TYPE_ERROR));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 签呈内容
     *
     * @param approvalBusinessList
     * @return
     */
    @GetMapping("/sign-data/{approvalBusinessList}")
    public AjaxResult signData(@PathVariable("approvalBusinessList") List<Integer> approvalBusinessList) {
        // 查询当前操作用户
        SysUser sysUser = iSysUserService.selectUserById(SecurityUtils.getUserId());
        if (null == sysUser) {
            return AjaxResult.error("用户不存在");
        }

        // 签呈推送列表
        Map<Integer, List<SysApprovalSendExt>> sendMap = new HashMap<>();

        // 查询签呈内容
        List<SysApprovalExt> sysApprovalExtList = iSysApprovalService.lastApprovalAndItem(approvalBusinessList, SecurityUtils.getPkCountry());
        if (CollectionUtil.isNotEmpty(sysApprovalExtList)) {
            // 签呈ID列表
            List<Integer> approvalIdList = sysApprovalExtList.stream().map(SysApprovalExt::getPkId).collect(Collectors.toList());
            // 签呈推送列表
            sendMap = iSysApprovalSendService.queryApprovalSendMap(approvalIdList);
        }

        Date nowDate = new Date();

        // 返回结果列表
        List<ApprovalBusinessVO> resultList = new ArrayList<>();

        for (Integer approvalBusiness : approvalBusinessList) {
            // 审批主体
            SysApprovalExt sysApproval = null;
            // 审批明细
            List<ApprovalBusinessDetailVO> detailList = new ArrayList<>();
            // 抄送人列表
            List<ApprovalBusinessSendVO> sendList = new ArrayList<>();

            for (SysApprovalExt sysApprovalExt : sysApprovalExtList) {
                if (approvalBusiness.equals(sysApprovalExt.getApprovalBusiness())) {
                    sysApproval = sysApprovalExt;
                }
            }
            if (null != sysApproval) {
                // 返回审批明细列表
                for (SysApprovalItemExt sysApprovalItemExt : sysApproval.getItemList()) {
                    detailList.add(ApprovalBusinessDetailVO.builder()
                            .approvalLevel(sysApprovalItemExt.getApprovalLevel())
                            .pkApprover(sysApprovalItemExt.getPkUser())
                            .approver(sysApprovalItemExt.getNickName())
                            .approverDept(sysApprovalItemExt.getDeptName())
                            .build());
                }

                // 返回审核抄送人列表
                List<SysApprovalSendExt> approvalSendList = sendMap.get(sysApproval.getPkId());
                if (CollectionUtil.isNotEmpty(approvalSendList)) {
                    for (SysApprovalSendExt sysApprovalSend : approvalSendList) {
                        sendList.add(ApprovalBusinessSendVO.builder()
                                .pkSend(sysApprovalSend.getPkUser())
                                .send(sysApprovalSend.getNickName())
                                .sendDept(sysApprovalSend.getDeptName())
                                .build());
                    }
                }
            }

            String approvalBusinessVal = null;
            if (EApprovalBusiness.CUSTOM.getValue() == approvalBusiness) {
                approvalBusinessVal = "";
            }
            // 不存在审批配置，没有明细
            resultList.add(ApprovalBusinessVO.builder()
                    .deptName(sysUser.getDeptName())
                    .userName(sysUser.getNickName())
                    .approvalBusiness(approvalBusiness)
                    .approvalBusinessVal(approvalBusinessVal)
                    .creationTime(nowDate)
                    .detailList(detailList)
                    .sendList(sendList)
                    .build());
        }

        return AjaxResult.success(resultList);
    }

}
