package com.sooka.applyData.service.impl;

import com.sooka.applyData.domain.DataDetailed;
import com.sooka.applyData.domain.DataRecord;
import com.sooka.applyData.mapper.DataRecordMapper;
import com.sooka.applyData.service.IDataRecordService;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 申请记录Service业务层处理
 *
 * @author yhliang
 * @date 2021-07-06
 */
@Service
public class DataRecordServiceImpl implements IDataRecordService
{
    @Resource
    private DataRecordMapper DataRecordMapper;

    /**
     * 查询申请记录
     *
     * @param id 申请记录ID
     * @return 申请记录
     */
    @Override
    public DataRecord selectDataRecordById(String id)
    {
        return DataRecordMapper.selectDataRecordById(id);
    }

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

    /**
     * 查询申请记录列表
     *
     * @param DataRecord 申请记录
     * @return 申请记录
     */
    @Override
    public List<DataRecord> selectDataRecordList(DataRecord DataRecord)
    {
        return DataRecordMapper.selectDataRecordList(DataRecord);
    }

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

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

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

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

    /**
     * 修改申请记录
     *
     * @param intBo 申请记录
     * @return 结果
     */
    @Override
    public int rejectDataRecord(DataRecord 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 DataRecordMapper.editDataRecord(intBo);
    }

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

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

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

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

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

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

    /**
     * 接口申请数量
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public String[] applyCount(String year, String deptId){
        Map map = DataRecordMapper.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;
    }

}
