package com.sooka.apply.service.impl;

import java.util.Iterator;
import java.util.List;

import com.sooka.common.core.text.Convert;
import com.sooka.common.utils.DateUtils;
import com.sooka.common.utils.uuid.IdUtils;
import com.sooka.framework.util.ShiroUtils;
import com.sooka.system.domain.SysUser;
import com.util.SecretKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;
import com.sooka.apply.domain.IntDetailed;
import com.sooka.apply.mapper.IntRecordMapper;
import com.sooka.apply.domain.IntRecord;
import com.sooka.apply.service.IIntRecordService;

/**
 * 申请记录Service业务层处理
 *
 * @author yhliang
 * @date 2021-07-06
 */
@Service
public class IntRecordServiceImpl implements IIntRecordService
{
    @Autowired
    private IntRecordMapper intRecordMapper;

    /**
     * 查询申请记录
     *
     * @param id 申请记录ID
     * @return 申请记录
     */
    @Override
    public IntRecord selectIntRecordById(String id)
    {
        return intRecordMapper.selectIntRecordById(id);
    }

    /**
     * 查询申请子表记录
     *
     * @param subId 申请子表记录ID
     * @return 申请记录
     */
    @Override
    public IntDetailed selectIntRecordDetailedBySubId(String subId){
        return intRecordMapper.selectIntRecordDetailedBySubId(subId);
    }

    /**
     * 查询申请记录列表
     *
     * @param intRecord 申请记录
     * @return 申请记录
     */
    @Override
    public List<IntRecord> selectIntRecordList(IntRecord intRecord)
    {
        return intRecordMapper.selectIntRecordList(intRecord);
    }

    /**
     * 查询申请记录明细
     *
     * @param intDetailed 查询条件
     * @return 申请明细集合
     */
    @Override
    public List<IntDetailed> selectIntDetailedList(IntDetailed intDetailed) {
        return intRecordMapper.selectIntDetailedList(intDetailed);
    }

    /**
     * 新增申请记录
     *
     * @param intRecord 申请记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertIntRecord(IntRecord intRecord)
    {
        /**添加主表**/
        SysUser sysUser = ShiroUtils.getSysUser();
        intRecord.setApplyDeptId(sysUser.getDept().getDeptId());
        intRecord.setApplyDeptName(sysUser.getDept().getDeptName());
        intRecord.setApplyUserId(sysUser.getUserId());
        intRecord.setApplyUserName(sysUser.getUserName());
        intRecord.setApplyTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD));
        intRecord.setStartTime(intRecord.getDuration().split(" - ")[0]);
        intRecord.setEndTime(intRecord.getDuration().split(" - ")[1]);
        //状态：0新建，政数局通过1，提供部门通过2，政数局待审批3，提供部门待审批4，政数局驳回5，提供部门驳回6
        intRecord.setStatus("0");
        /**添加后返回主表ID**/
        intRecordMapper.insertIntRecord(intRecord);
        /**添加子表**/
        return insertIntDetailed(intRecord.getId(),intRecord.getDuration(),intRecord.getIntDetailedList());
    }

    /**
     * 修改申请记录
     *
     * @param intRecord 申请记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editIntRecord(IntRecord intRecord){
        /**添加主表**/
        SysUser sysUser = ShiroUtils.getSysUser();
        intRecord.setApplyDeptId(sysUser.getDept().getDeptId());
        intRecord.setApplyDeptName(sysUser.getDept().getDeptName());
        intRecord.setApplyUserId(sysUser.getUserId());
        intRecord.setApplyUserName(sysUser.getUserName());
        intRecord.setApplyTime(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD));
        intRecord.setStartTime(intRecord.getDuration().split(" - ")[0]);
        intRecord.setEndTime(intRecord.getDuration().split(" - ")[1]);
        //状态：0新建，政数局通过1，提供部门通过2，政数局待审批3，提供部门待审批4，政数局驳回5，提供部门驳回6
        intRecord.setStatus("0");
        /**修改主表**/
        intRecordMapper.editIntRecord(intRecord);
        /**删除子表**/
        intRecordMapper.deleteIntDetailedByRecordIds(Convert.toStrArray(intRecord.getId()));
        /**添加子表**/
        return insertIntDetailed(intRecord.getId(),intRecord.getDuration(),intRecord.getIntDetailedList());
    }

    /**
     * 提交审核
     * @return 结果
     */
    @Override
    public int updateStatus(String id, String status){
        return intRecordMapper.updateStatus(id,status);
    }

    /**
     * 修改申请记录
     *
     * @param intBo 申请记录
     * @return 结果
     */
    @Override
    public int rejectIntRecord(IntRecord intBo){
        SysUser sysUser = ShiroUtils.getSysUser();
        //如果是政数局驳回,status = 5
        String zsj_reject = "3";
        if(zsj_reject.equals(intBo.getStatus())){
            intBo.setApprovalUserId(sysUser.getUserId().toString());
            intBo.setApprovalUserName(sysUser.getUserName());
            intBo.setApprovalTime(DateUtils.getDate());
            intBo.setApprovalFile(intBo.getFile());
            intBo.setApprovalContent(intBo.getContent());
            intBo.setStatus("5");
        }else{
            //否则 status = 6
            intBo.setExamineUserId(sysUser.getUserId().toString());
            intBo.setExamineUserName(sysUser.getUserName());
            intBo.setExamineTime(DateUtils.getDate());
            intBo.setExamineFile(intBo.getFile());
            intBo.setExamineContent(intBo.getContent());
            intBo.setStatus("6");
        }
        return intRecordMapper.editIntRecord(intBo);
    }

    /**
     * 删除申请记录对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteIntRecordByIds(String ids)
    {
        intRecordMapper.deleteIntDetailedByRecordIds(Convert.toStrArray(ids));
        return intRecordMapper.deleteIntRecordByIds(Convert.toStrArray(ids));
    }

    /**
     * 状态修改
     *
     * @param intDetailed 接口信息
     * @return 结果
     */
    @Override
    public int changeStatus(IntDetailed intDetailed) {
        System.out.println(intDetailed.toString());
        return intRecordMapper.changeStatus(intDetailed);
    }

    /**
     * 新增申请明细信息
     *
     * @param list 申请记录对象
     */
    private int insertIntDetailed(String id, String duration, List<IntDetailed> list){

        String deptId = ShiroUtils.getSysUser().getDept().getDeptId().toString();
        String deptName = ShiroUtils.getSysUser().getDept().getDeptName();

        List<IntDetailed> list_ = new ArrayList<IntDetailed>();
        for (int i = 0; i < list.size(); i++) {
            String content = deptId+"/"+deptName+"/"+duration+"/"+IdUtils.fastSimpleUUID();
            IntDetailed intDetailed = new IntDetailed();
            intDetailed.setRecordId(id);
            intDetailed.setIntId(list.get(i).getIntId());
            intDetailed.setSecretKey(SecretKeyUtil.AESEncode("3fc674da58",content));
//            intDetailed.setSecretContent(content);
            intDetailed.setPurpose(list.get(i).getPurpose());
            intDetailed.setFile(list.get(i).getFile());
            list_.add(intDetailed);
        }
        if (list_.size() > 0) {
            return intRecordMapper.batchIntDetailed(list_);
        }
        return 0;
    }

    /**
     * 接口申请频次
     * @param shareTypes 接口类型
     * @return 结果
     */
    @Override
    public String[] applyFrequency(String[] shareTypes){
        Map map = intRecordMapper.applyFrequency(shareTypes);
        return Map2Array(map);
    }

    /**
     * 接口申请数量
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public String[] applyCount(String year, String deptId){
        Map map = intRecordMapper.applyCount(year,deptId);
        return Map2Array(map);
    }

    /**
     * Map转二维数组
     * @param map
     * @return
     */
    public static String[] Map2Array(Map map) {
        String[] strings = null;
        if (map != null && !map.isEmpty()) {
            int size = map.size();
            strings = new String[size];

            Iterator iterator = map.entrySet().iterator();
            for (int i = 0; i < size; i++) {
                Map.Entry entry = (Map.Entry) iterator.next();
                Object value = entry.getValue();
                strings[i] = String.valueOf(value);
            }
        }
        return strings;
    }

}
