package org.dromara.system.service.impl.pay;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;

import org.dromara.common.mybatis.core.domain.BaseEntity;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.pay.XiaoyuanPay;
import org.dromara.system.domain.pay.bo.XiaoyuanPayBo;
import org.dromara.system.domain.pay.vo.XiaoyuanPayVo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.mapper.pay.XiaoyuanPayMapper;
import org.dromara.system.service.impl.SysDictTypeServiceImpl;
import org.dromara.system.service.pay.IXiaoyuanPayService;
import org.springframework.stereotype.Service;
import java.util.*;


/**
 * 教职工工资条Service业务层处理
 *
 * @author boman
 * @date 2023-09-05
 */
@RequiredArgsConstructor
@Service
public class XiaoyuanPayServiceImpl implements IXiaoyuanPayService {

    private final XiaoyuanPayMapper baseMapper;

    private final SysDictTypeServiceImpl sysDictTypeService;

    /**
     * 查询教职工工资条
     */
    @Override
    public XiaoyuanPayVo queryById(Long payId) {
        return baseMapper.selectVoById(payId);
    }

    /**
     * 查询教职工工资条列表
     */
    @Override
    public Page<XiaoyuanPayVo> queryPageList(XiaoyuanPayBo bo, PageQuery pageQuery) {

        //todo 获取自己的工号 如果是当前有学校角色,则不获取
        if(!LoginHelper.isSuperAdmin() && !LoginHelper.isTenantSchool()){
            String username = LoginHelper.getLoginUser().getUsername();
            bo.setTeacherNum(username);
        }
        LambdaQueryWrapper<XiaoyuanPay> lqw = buildQueryWrapper(bo);
        Page<XiaoyuanPayVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        //处理的返回值List
        List<XiaoyuanPayVo> resultList = new ArrayList<>();
        XiaoyuanPayVo vo = new XiaoyuanPayVo();
        List<XiaoyuanPayVo> records = result.getRecords();
        List<JSONObject> detailList = new ArrayList<>();
        if (records != null && records.size() > 0) {
            for (XiaoyuanPayVo record : records) {
                String tableDetail = record.getTableDetail();
                Map<String, Object> stringMap = mapStringToMap(tableDetail);
                stringMap.put("payId", record.getPayId());
                detailList.add(new JSONObject(stringMap));
            }
            //vo.setTableLabelJA(JSONUtil.parseArray(records.get(0).getTableHead()));
            vo.setTableDataJO(detailList);
        }
        resultList.add(vo);
        result.setRecords(resultList);
        return result;
    }

    /**
     * 将Map字符串转换为Map
     *
     * @param str Map字符串
     * @return Map
     */
    public static Map<String, Object> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, Object> map = new HashMap<String, Object>();
        for (String string : strs) {
            String key = string.split("=")[0];
            String value = string.split("=")[1];
            // 去掉头部空格
            String key1 = key.trim();
            String value1 = value.trim();
            map.put(key1, value1);
        }
        return map;
    }

    /**
     * 查询教职工工资条列表
     */
    @Override
    public List<XiaoyuanPayVo> queryList(XiaoyuanPayBo bo) {
        LambdaQueryWrapper<XiaoyuanPay> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<XiaoyuanPay> buildQueryWrapper(XiaoyuanPayBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<XiaoyuanPay> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTeacherNum()), XiaoyuanPay::getTeacherNum, bo.getTeacherNum());
        lqw.eq(bo.getTeacherId() != null, XiaoyuanPay::getTeacherId, bo.getTeacherId());
        lqw.eq(StringUtils.isNotBlank(bo.getTableHead()), XiaoyuanPay::getTableHead, bo.getTableHead());
        lqw.eq(StringUtils.isNotBlank(bo.getTableDetail()), XiaoyuanPay::getTableDetail, bo.getTableDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getPayTime()), XiaoyuanPay::getPayTime, bo.getPayTime());
        lqw.eq(StringUtils.isNotBlank(bo.getYear()), XiaoyuanPay::getYear, bo.getYear());
        lqw.eq(StringUtils.isNotBlank(bo.getMonth()), XiaoyuanPay::getMonth, bo.getMonth());
        lqw.orderByDesc(XiaoyuanPay::getCreateTime);
        return lqw;
    }

    /**
     * 新增教职工工资条
     */
    @Override
    public Boolean insertByBo(XiaoyuanPayBo bo) {
        XiaoyuanPay add = MapstructUtils.convert(bo, XiaoyuanPay.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPayId(add.getPayId());
        }
        return flag;
    }

    /**
     * 修改教职工工资条
     */
    @Override
    public Boolean updateByBo(XiaoyuanPayBo bo) {
        XiaoyuanPay update = MapstructUtils.convert(bo, XiaoyuanPay.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(XiaoyuanPay entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除教职工工资条
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 教职工工资表导入数据
     *
     * @param maps
     */
    @Override
    public void importData(List<Map<String, String>> maps) {
        //去字典值中匹配学科名称 sys_subject
        List<SysDictDataVo> sysSubject = sysDictTypeService.selectDictDataByType("wages");
        //工资条所需要的所有表头信息
        List<JSONObject> sysDictList = new ArrayList<>();
        for (SysDictDataVo sysDictDataVo : sysSubject) {
            Map<String, Object> sysDictMap = new HashMap<>();
            sysDictMap.put("label", sysDictDataVo.getDictLabel());
            sysDictMap.put("prop", sysDictDataVo.getDictLabel());
            sysDictList.add(new JSONObject(sysDictMap));
        }
        List<XiaoyuanPayBo> boList = new ArrayList<>();
        for (Map<String, String> map : maps) {
            XiaoyuanPayBo bo = new XiaoyuanPayBo();
            //组装数据
            bo.setTeacherName(map.get("姓名"));
            bo.setTeacherNum(map.get("手机号"));
            String faTime = map.get("发放时间");
            String[] split = faTime.split("-");
            if (split.length > 1) {
                bo.setYear(split[0]);
                bo.setMonth(split[1]);
            }
            bo.setPayTime(faTime);
            bo.setTableHead(sysDictList.toString());
            bo.setTableDetail(map.toString());
            bo.setCreateTime(DateUtils.getNowDate());
            boList.add(bo);
        }
        baseMapper.insertBatch(MapstructUtils.convert(boList, XiaoyuanPay.class));
    }

}
