package com.lightinit.hsdataplatform.impl.admin;

import com.lightinit.hsdataplatform.common.OrderNumberUtils;
import com.lightinit.hsdataplatform.dictionary.*;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.mapper.*;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IContractService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class ContractServiceImpl implements IContractService {

    @Autowired
    private AdminRoleMapper adminRoleMapper ;

    @Autowired
    private ContractMapper contractMapper ;

    @Autowired
    private ContractResourceMapper contractResourceMapper ;

    @Autowired
    private PublishInfoMapper publishInfoMapper ;

//    @Autowired
//    private ResourceAuthMapper resourceAuthMapper ;
//
//    @Autowired
//    private OrderMapper orderMapper ;
//
//    @Autowired
//    private OrderGoodsMapper orderGoodsMapper ;



    @Override
    public List<ContractListModel> queryList(ContractSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return contractMapper.queryList(inputModel);
    }

    @Override
    public long queryCount(ContractSearchModel inputModel) {
        return contractMapper.queryCount(inputModel) ;
    }

    @Override
    public int isAdminFalg(Long id) {
        return adminRoleMapper.isAdminFalg(id);
    }

    @Override
    public List<ContractResourceListModel> resourceList(ContractResourceSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.resourceList(inputModel);
    }

    @Override
    public long resourceCount(ContractResourceSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return publishInfoMapper.resourceCount(inputModel);
    }

    @Override
    @Transactional
    public ResultState addFinally(ContractAddModel input, Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        Date createdAt = new Date() ;

        //插入contract合同表
        ContractWithBLOBs contract = new ContractWithBLOBs() ;
        BeanUtils.copyProperties(input,contract);
        contract.setUserId(id);
        contract.setCreatedAt(createdAt);
        contract.setCreatedBy(id);
        contract.setContractTime(createdAt);
        contract.setContractState(DicContractState.NO_EFFECT);
        int result1 = contractMapper.insert(contract) ;

//        //插入order表
//        Order order = new Order() ;
//        order.setPlatformType(DicPlatformType.OPEN);
//        order.setUserId(id);
//        order.setOrderTime(createdAt);
//        order.setOrderNumber(OrderNumberUtils.generate());
//        order.setOrderType(DicOrderType.OFFLINEORDER);
//        order.setOrderState(DicOrderState.NOTPAID);
//        order.setOrderAmount(input.getContractAmount());
//        order.setCreatedAt(createdAt);
//        order.setCreatedBy(id);
//        int result2 = orderMapper.insert(order) ;

        List<ContractResourceAddModel> contractResourceAddModels = input.getContractAddResourceModelList() ;
        if (contractResourceAddModels!=null) {
            if (contractResourceAddModels.size() > 0) {
                for (ContractResourceAddModel contractResourceAddModel : contractResourceAddModels) {
                    if (StringUtils.isNotEmpty(contractResourceAddModel.getChargeMethod())) {
                        //插入contract_resource
                        ContractResource contractResource = new ContractResource();
                        BeanUtils.copyProperties(contractResourceAddModel, contractResource);
                        contractResource.setContractId(contract.getId());
                        contractResource.setCreatedAt(createdAt);
                        contractResource.setCreatedBy(id);
                        contractResourceMapper.insert(contractResource);

//                    //插入resource_auth
//                    ResourceAuth resourceAuth = new ResourceAuth() ;
//                    resourceAuth.setPlatformType(DicPlatformType.OPEN);
//                    resourceAuth.setPublishInfoId(contractResourceAddModel.getPublishInfoId());
//                    resourceAuth.setAuthState(DicAuthorizationState.AUTHORIZE_OK);
//                    resourceAuth.setApplier(id);
//                    resourceAuth.setApplyTime(createdAt);
//                    resourceAuth.setCreatedAt(createdAt);
//                    resourceAuth.setCreatedBy(id);
//                    resourceAuthMapper.insert(resourceAuth) ;

//                    //插入order_goods
//                    OrderGoods orderGoods = new OrderGoods() ;
//                    orderGoods.setOrderId(order.getId());
//                    orderGoods.setResourceAuthId(resourceAuth.getId());
//                    orderGoods.setResourceType(contractResourceAddModel.getResourceType());
//                    orderGoods.setResourceName(contractResourceAddModel.getResourceName());
//                    orderGoods.setQuantity(1);
//                    orderGoods.setChargeMethod(contractResourceAddModel.getChargeMethod());
//                    orderGoods.setPackagePrice(contractResourceAddModel.getPrice());
//                    orderGoods.setEffectiveDate(contractResourceAddModel.getEffectiveDate());
//                    orderGoods.setExpiriedDate(contractResourceAddModel.getExpiriedDate());
//                    orderGoods.setCreatedAt(createdAt);
//                    orderGoods.setCreatedBy(id);
//                    orderGoodsMapper.insert(orderGoods) ;
                    }
                }
            }
        }
        if (!(result1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }
        resultState.setData(contract.getId());
        return resultState;

    }

    @Override
    public ContractViewModel queryOne(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ContractViewModel contractViewModel = new ContractViewModel() ;
        //查询contract表
        ContractWithBLOBs contractWithBLOBs = contractMapper.selectByPrimaryKey(id) ;
        BeanUtils.copyProperties(contractWithBLOBs,contractViewModel);

        //查询contract_resource
        ContractResourceExample example = new ContractResourceExample() ;
        ContractResourceExample.Criteria criteria = example.createCriteria() ;
        criteria.andContractIdEqualTo(contractWithBLOBs.getId()) ;
        List<ContractResource> contractResourceList = contractResourceMapper.selectByExample(example) ;
        if (contractResourceList!=null) {
            if (contractResourceList.size() > 0) {
                List<ContractResourceAddModel> contractAddResourceModelList = new ArrayList<>();
                for (ContractResource contractResource : contractResourceList) {
                    ContractResourceAddModel contractResourceAddModel = new ContractResourceAddModel();
                    BeanUtils.copyProperties(contractResource, contractResourceAddModel);
                    ContractResourceResultModel contractResourceResultModel = publishInfoMapper.getResourceByPublishInfoId(contractResource.getPublishInfoId());
                    String contractResourceName = "";
                    if (StringUtils.isNotEmpty(contractResourceResultModel.getResourceType())) {
                        contractResourceName = contractResourceName + contractResourceResultModel.getResourceType() + ">";
                    }
                    if (StringUtils.isNotEmpty(contractResourceResultModel.getCatelogName())) {
                        contractResourceName = contractResourceName + contractResourceResultModel.getCatelogName() + ">";
                    }
                    contractResourceName = contractResourceName + contractResourceResultModel.getResourceName();
                    contractResourceAddModel.setContractResourceName(contractResourceName);
                    contractAddResourceModelList.add(contractResourceAddModel);
                }
                contractViewModel.setContractAddResourceModelList(contractAddResourceModelList);
            }
        }

        return contractViewModel;
    }

    @Override
    public ResultState<Long> contractStop(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>() ;
        ContractWithBLOBs contractWithBLOBs = new ContractWithBLOBs();
        contractWithBLOBs.setContractState(DicContractState.OVERDUE);
        contractWithBLOBs.setId(id);
        ContractExample  example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        int result = contractMapper.updateByExampleSelective(contractWithBLOBs,example) ;
        if (!(result>0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("终止失败");
        }
        resultState.setData(id);
        return resultState ;
    }

    @Override
    @Transactional
    public ResultState editFinally(ContractEditModel input, Long userId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        Date createdAt = new Date() ;

        //更新contract合同表
        ContractWithBLOBs contract = new ContractWithBLOBs() ;
        BeanUtils.copyProperties(input,contract);
        ContractExample example = new ContractExample() ;
        ContractExample.Criteria criteria = example.createCriteria() ;
        criteria.andIdEqualTo(input.getId()) ;
        int result1 = contractMapper.updateByExampleSelective(contract,example) ;

        //删除contract_resource中需要删除的数据
        if (input.getDeleteResourceList()!=null) {
            if (input.getDeleteResourceList().size() > 0) {
                for (Long resourceId : input.getDeleteResourceList()) {
                    contractResourceMapper.deleteByPrimaryKey(resourceId);
                }
            }
        }

        //插入新增contract_resource数据
        List<ContractResourceAddModel> contractResourceAddModels = input.getContractAddResourceModelList() ;
        if (contractResourceAddModels!=null) {
            if (contractResourceAddModels.size() > 0) {
                for (ContractResourceAddModel contractResourceAddModel : contractResourceAddModels) {
                    if (StringUtils.isNotEmpty(contractResourceAddModel.getChargeMethod())) {
                        //插入contract_resource
                        ContractResource contractResource = new ContractResource();
                        BeanUtils.copyProperties(contractResourceAddModel, contractResource);
                        contractResource.setContractId(input.getId());
                        contractResource.setCreatedAt(createdAt);
                        contractResource.setCreatedBy(userId);
                        contractResourceMapper.insert(contractResource);
                    }
                }
            }
        }
        if (!(result1 > 0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据插入失败");
        }
        resultState.setData(contract.getId());
        return resultState;

    }

    @Override
    public ResultState<Long> contractDelete(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>() ;
        //删除contract_resource表
        ContractResourceExample example = new ContractResourceExample() ;
        ContractResourceExample.Criteria criteria = example.createCriteria() ;
        criteria.andContractIdEqualTo(id) ;
        contractResourceMapper.deleteByExample(example) ;
        //删除contract表
        int result = contractMapper.deleteByPrimaryKey(id) ;
        if (!(result>0)){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("删除失败");
        }
        resultState.setData(id);
        return resultState;
    }
}
