package com.dk.mdm.service.mst;

import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.infrastructure.enums.ErrorCodeEnum;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseCodeEnum;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.mst.DictionaryDataConvert;
import com.dk.mdm.infrastructure.util.AuthUtils;
import com.dk.mdm.mapper.mst.MoneyAccountMapper;
import com.dk.mdm.model.pojo.mst.DictionaryData;
import com.dk.mdm.mapper.mst.DictionaryDataMapper;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.pojo.mst.Warehouse;
import com.dk.mdm.model.query.mst.DictionaryDataQuery;
import com.dk.mdm.model.query.mst.MoneyAccountQuery;
import com.dk.mdm.model.response.mst.DictionaryDataResponse;
import com.dk.mdm.model.response.mst.MoneyAccountResponse;
import com.dk.mdm.model.vo.mst.DictionaryDataVO;
import com.dk.mdm.model.vo.mst.MoneyAccountVO;
import com.dk.mdm.model.vo.mst.WarehouseVO;
import com.dk.mdm.service.common.CommonService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class DictionaryDataService extends BaseService<DictionaryData> {

    @Override
    public BaseMapper<DictionaryData> getRepository() {
        return dictionaryDataMapper;
    }

    @Autowired
    private DictionaryDataMapper dictionaryDataMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private DictionaryDataConvert dictionaryDataConvert;

    @Autowired
    private MoneyAccountService moneyAccountService;

    @Autowired
    private AuthUtils authUtils;

    /**
     * @desc : 重写主键
     * @author : 于继渤
     * @date : 2024/2/29 20:29
     */
    @Override
    public String getPrimaryKey() {
        return "data_id";
    }

    /**
     * @desc : 查询
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    @Pagination
    public ResponseResultVO<PageList<DictionaryDataResponse>> selectByCond(DictionaryDataQuery dictionaryDataQuery) {
        return super.mergeListWithCount(dictionaryDataQuery, dictionaryDataMapper.selectByCond(dictionaryDataQuery),
                dictionaryDataMapper.countByCond(dictionaryDataQuery));
    }

    public ResponseResultVO<Long> countByCondMoneyAccount(String id) {
        Long aLong = dictionaryDataMapper.countByCondMoneyAccount(id);
        return ResponseResultUtil.success(aLong);
    }

    /**
     * @desc : 新建
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> insert(DictionaryDataVO dictionaryDataVO) {
        //实体转换
        DictionaryData dictionaryData = dictionaryDataConvert.convertToPo(dictionaryDataVO);
        Map<String, Object> map = new HashMap<>();
        map.put("dictCode", dictionaryDataVO.getDictCode());
        //设置序号
        dictionaryData.setDisplayNo(commonService.getMaxDisplayNo(Constant.DisplayNoTable.DICTIONARYDATA, map));
        //设置编码
        Map<String, Object> uniqueNoteCode = commonService.getUniqueNoteCode(dictionaryDataVO.getDictCode(), true);
        dictionaryData.setDataId(uniqueNoteCode.get("outId").toString());
        dictionaryData.setDataCode(uniqueNoteCode.get("outNote").toString());

        // 标准版账户类别新建要在资金账户表里插入一条一样的，编辑时两个表一起更新；专业版逻辑不变
        if (dictionaryDataVO.getDictCode().equals("基础资料-账户") && dictionaryDataVO.getGradeCode() != null && dictionaryDataVO.getGradeCode().equals("STD")) {
            //新建资金账户
            String staffId = authUtils.getStaff().getStaffId();
            moneyAccountService.insert(new MoneyAccountVO().setAccDate(LocalDate.now())
                    .setBalance(new BigDecimal(0)).setInitBalance(new BigDecimal(0))
                    .setMacName(dictionaryDataVO.getDataValue()).setMacType(dictionaryData.getDataId()).setMakeStaff(staffId).setStaffId(staffId).setOrgId(dictionaryDataVO.getOrgId()));
        }
        //新建
        dictionaryDataMapper.insert(dictionaryData);
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 编辑
     * @author : 于继渤
     * @date : 2023/1/5 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> update(DictionaryDataVO dictionaryDataVO) {
        DictionaryData dictionaryData = dictionaryDataConvert.convertToPo(dictionaryDataVO);
        DictionaryData dictionaryDataItem = dictionaryDataMapper.selectById(dictionaryDataVO.getDataId());
        if (dictionaryDataItem.getSysCode() != null) {
            //系统预制 无法编辑
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.SYSTEM_PRESET_DATA_UNABLE_TO_OPERATE.getMessage());
        }
        DictionaryData dictionaryData1 = dictionaryDataMapper.selectById(dictionaryDataVO.getDataId());
        if ((dictionaryData1.getFlgDefault() == null || !dictionaryData1.getFlgDefault()) && dictionaryDataVO.getFlgDefault() != null && dictionaryDataVO.getFlgDefault()) {
            //默认  把其他置为非默认
            dictionaryDataMapper.updateFlgDefault(new DictionaryDataQuery().setCpId(dictionaryData1.getCpId()).setDictCode(dictionaryData1.getDictCode()));
        }

        if (dictionaryDataVO.getDictCode().equals("基础资料-账户") && dictionaryDataVO.getGradeCode() != null && dictionaryDataVO.getGradeCode().equals("STD")) {
            //编辑资金账户
            ResponseResultVO<PageList<MoneyAccountResponse>> pageListResponseResultVO = moneyAccountService.selectByCond(new MoneyAccountQuery().setMacType(dictionaryDataVO.getDataValue()).setCpId(authUtils.getStaff().getCpId()));
            if(pageListResponseResultVO.getData().getList() != null && pageListResponseResultVO.getData().getList().size() > 0){
                MoneyAccountResponse moneyAccountResponse = pageListResponseResultVO.getData().getList().get(0);
                moneyAccountService.update(new MoneyAccountVO().setAccDate(LocalDate.now())
                        .setBalance(new BigDecimal(0)).setInitBalance(new BigDecimal(0))
                        .setMacName(dictionaryDataVO.getDataValue()).setMacType(dictionaryData.getDataId()).setMacId(moneyAccountResponse.getMacId()));
            }




        }
        super.updateByUuid(dictionaryData);
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 停用
     * @author : 于继渤
     * @date :  2023/1/4 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<Boolean> disable(String id) {
        DictionaryData dictionaryDataItem = dictionaryDataMapper.selectById(id);
        if (dictionaryDataItem.getSysCode() != null) {
            //系统预制 无法编辑
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.SYSTEM_PRESET_DATA_UNABLE_TO_OPERATE.getMessage());
        }
        super.disable(id);

        return ResponseResultUtil.success();
    }

    /**
     * @desc : 启用
     * @author : 于继渤
     * @date :  2023/1/4 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<Boolean> enable(String id) {
        DictionaryData dictionaryDataItem = dictionaryDataMapper.selectById(id);
        if (dictionaryDataItem.getSysCode() != null) {
            //系统预制 无法编辑
            return ResponseResultUtil.error(ResponseCodeEnum.OPERATE_FAIL.getCode(), ErrorCodeEnum.SYSTEM_PRESET_DATA_UNABLE_TO_OPERATE.getMessage());
        }
        super.enable(id);
        return ResponseResultUtil.success();
    }


    /**
     * @desc : 批量编辑序号
     * @author : 于继渤
     * @date :  2023/1/4 9:39
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> updateBatchDictionaryDataDisplayNo(DictionaryDataVO dictionaryDataVO) {
        dictionaryDataMapper.updateBatchDictionaryDataDisplayNo(dictionaryDataVO.getDataIds());
        return ResponseResultUtil.success();
    }
}
