package com.lightinit.hsdataplatform.impl.admin;

import com.lightinit.hsdataplatform.dictionary.DicInvoiceState;
import com.lightinit.hsdataplatform.entity.Invoice;
import com.lightinit.hsdataplatform.entity.User;
import com.lightinit.hsdataplatform.mapper.InvoiceMapper;
import com.lightinit.hsdataplatform.mapper.UserMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.InvoiceService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class InvoiceServiceImpl implements InvoiceService {
    @Autowired
    private InvoiceMapper invoiceMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<InvoiceListModel> queryList(InvoiceSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return invoiceMapper.queryList(inputModel);
    }

    @Override
    public long queryCount(InvoiceSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return invoiceMapper.queryCount(inputModel);
    }

    @Override
    public ResultState doAdd(InvoiceAddModel inputmodel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<Long>();
        Invoice model = new Invoice();
        if(inputmodel.getInvoicedAt()==null) {
            inputmodel.setInvoicedAt(new Date());
        }
        int sqlResult =0;
        BeanUtils.copyProperties(inputmodel,model);
        model.setInvoiceState(DicInvoiceState.INVOICED);
        model.setApplyTime(new Date());
        if(inputmodel.getId()==null) {
            sqlResult = invoiceMapper.insert(model);
        }else {
            sqlResult = invoiceMapper.updateByPrimaryKeySelective(model);
        }

        if (!(sqlResult > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("开票失败");
        }
        resultState.setData(inputmodel.getId());
        return resultState;
    }

    @Override
    public UserModel userView(Long userId) {
        return userMapper.selectByuserId(userId);
    }

    @Override
    public InvoiceViewModel toDetail(Long id) {

        return invoiceMapper.toDetail(id);
    }
}
