package com.dk.mdm.service.mst;

import com.dk.common.infrastructure.annotaiton.Pagination;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.mdm.infrastructure.convert.mst.SupplierConvert;
import com.dk.mdm.infrastructure.util.AuthUtils;
import com.dk.mdm.mapper.common.CommonMapper;
import com.dk.mdm.mapper.mac.OtherPayableMapper;
import com.dk.mdm.model.pojo.mst.Supplier;
import com.dk.mdm.mapper.mst.SupplierMapper;
import com.dk.common.service.BaseService;
import com.dk.common.mapper.BaseMapper;
import com.dk.mdm.model.query.mac.MacTransferItemQuery;
import com.dk.mdm.model.query.mac.OtherPayableQuery;
import com.dk.mdm.model.query.mst.SupplierQuery;
import com.dk.mdm.model.response.mac.MacTransferItemResponse;
import com.dk.mdm.model.response.mac.MacTransferResponse;
import com.dk.mdm.model.response.mac.OtherPayableResponse;
import com.dk.mdm.model.response.mst.SpplierResponse;
import com.dk.mdm.model.vo.mac.OtherPayableItemVO;
import com.dk.mdm.model.vo.mac.OtherPayableVO;
import com.dk.mdm.model.vo.mst.SupplierVo;
import com.dk.mdm.service.common.CommonService;
import com.dk.mdm.service.mac.OtherPayableService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

@Service
@Transactional
public class SupplierService extends BaseService<Supplier> {
    /**
     * @desc : 重写主键
     * @author : 王英杰
     * @date : 2023/1/9 10:39
     */
    @Override
    public String getPrimaryKey() {
        return "sup_id";
    }

    @Override
    public BaseMapper<Supplier> getRepository() {
        return supplierMapper;
    }

    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private AuthUtils authUtils;

    @Autowired
    private SupplierConvert supplierConvert;
    @Autowired
    private CommonService commonService;

    @Autowired
    private OtherPayableService otherPayableService;
    @Autowired
    private OtherPayableMapper otherPayableMapper;
    @Autowired
    private CommonMapper commonMapper;

    /**
     * @desc : 条件查询
     * @author : 王英杰
     * @date : 2023/1/10 17:19
     */
    @Pagination
    public ResponseResultVO<PageList<Supplier>> selectByCond(SupplierQuery supplierQuery) {
        List<SpplierResponse> list = new ArrayList<>();
        list = supplierMapper.selectByCond(supplierQuery);
        for (int i = 0; i < list.size(); i++) { //显示明细第一条的 内容
            list.get(i).getSupId();
            // 转账明细
            List<OtherPayableResponse> itemList = otherPayableMapper.selectByCond(new OtherPayableQuery().setObjectId(list.get(i).getSupId()).setBusinessType(0));
            if (itemList.size() > 0) {
                BigDecimal sumAmtPayableValue = (itemList != null && !itemList.isEmpty() && itemList.get(0).getSumAmtPayable() != null) ?
                        itemList.get(0).getSumAmtPayable() :
                        BigDecimal.ZERO;
                list.get(i).setSumAmtPayable(sumAmtPayableValue);
            }
        }
        return super.mergeListWithCount(supplierQuery, list,
                supplierMapper.countByCond(supplierQuery));
    }

    /**
     * @desc : 停用 供应商
     * @author : 王英杰
     * @date : 2023/1/10 17:19
     */
    public ResponseResultVO<?> deactivateData(SupplierVo supplierVo) {
        return super.disable(supplierVo.getSupId());
    }

    /**
     * @desc : 新建供应商
     * @author : 王英杰
     * @date : 2024/2/27 9:17
     */
    @Transactional(rollbackFor = {Exception.class})
    public ResponseResultVO<?> insert(SupplierVo supplierVo) {
        // 转化实体
        Supplier supplier = supplierConvert.convertToPo(supplierVo);
        Map<String, Object> codeMap = commonService.getUniqueNoteCode(Constant.docNameConstant.SUPPLIER.getName(), true);
        supplier.setSupId(codeMap.get("outId").toString());
        supplier.setSupCode(codeMap.get("outNote").toString());  //插入供应商表的实体
        super.insert(supplier);// 先插入自己的供应商表
        if ((supplier.getBrandIds() != null) && (supplier.getBrandIds().size() > 0)) {  //如果有 商品品牌 一起插入品牌
            List<Supplier> Supplierlst = new ArrayList<>();
            List<String> BrandIdList = new ArrayList<>();
            BrandIdList = supplier.getBrandIds();
            Supplier supplier_center = null;
            for (int i = 0; i < BrandIdList.size(); i++) {
                supplier_center = new Supplier();
                supplier_center.setBrandId(BrandIdList.get(i));
                supplier_center.setSupId(supplier.getSupId());
                Supplierlst.add(supplier_center);
            }
            supplierMapper.insertSupplierBrandtBatch(Supplierlst); // 向供应商品牌表插入数据
        }
        if (supplierVo.getStartAmount() != null && supplierVo.getStartAmount().compareTo(BigDecimal.ZERO) > 0) { //说明有起始欠款  需要插入其他支出
            //先组装明细
            List<OtherPayableItemVO> itemList = new ArrayList<>();
            OtherPayableItemVO otherPayableItemVO = new OtherPayableItemVO();
            Map<String, Object> param = new HashMap<>();
            param.put("cpId", authUtils.getStaff().getCpId());
            param.put("dictCode", "基础资料-支出");
            param.put("dataValue", "期初");
            Map<String, Object> data = commonMapper.selectDictionaryData(param);
            String dataId = String.valueOf(data.get("dataId"));
            otherPayableItemVO.setPayableType(dataId);
            otherPayableItemVO.setAmtPayable(supplierVo.getStartAmount());
            itemList.add(otherPayableItemVO);
            //调用 新建其他支出
            OtherPayableVO otherPayableVO = new OtherPayableVO().setBusinessType(0).setObjectId(supplier.getSupId())
                    .setSumAmtPayable(supplierVo.getStartAmount()).setStaffId(supplier.getStaffId())
                    .setOrgId(supplier.getOrgId()).setAccDate(LocalDate.now()).setMakeStaff(supplierVo
                            .getMakeStaff()).setItemList(itemList).setSumAmtPay(BigDecimal.ZERO);
            otherPayableService.insert(otherPayableVO);
        }
        return ResponseResultUtil.success();
    }

    /**
     * @desc : 编辑方法
     * @author : 王英杰
     * @date : 2023/1/9 10:49
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public ResponseResultVO<?> update(SupplierVo supplierVo) {
        // 转化实体
        Supplier supplier = supplierConvert.convertToPo(supplierVo);
        super.updateByUuid(supplier);// 先更新的供应商表
        if ((supplier.getBrandIds() != null) && (supplier.getBrandIds().size() > 0)) {  //如果有 商品品牌 一起插入品牌
            supplierMapper.batchDeleteBrand(supplier.getSupId());//批量删除供应商对应的供应商品牌
            List<Supplier> supplierlst = new ArrayList<>();
            List<String> BrandIdList = new ArrayList<>();
            BrandIdList = supplier.getBrandIds();
            Supplier supplier_center = null;
            for (int i = 0; i < BrandIdList.size(); i++) {
                supplier_center = new Supplier();
                supplier_center.setBrandId(BrandIdList.get(i));
                supplier_center.setSupId(supplier.getSupId());
                supplierlst.add(supplier_center);
            }
            supplierMapper.insertSupplierBrandtBatch(supplierlst); // 向供应商品牌表插入数据
        }
        return ResponseResultUtil.success();

    }
}
