package com.sifang.modules.supply.setting.service;

import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.kingdee.bos.webapi.entity.RepoStatus;
import com.kingdee.bos.webapi.entity.SuccessEntity;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.sifang.modules.kingdee.constants.KingDeeConstants;
import com.sifang.modules.kingdee.util.KingDeeUtil;
import com.sifang.modules.kingdee.vo.KingDeeResponseVo;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.dao.CrmSupplyMaterialTypeDao;
import com.sifang.modules.supply.setting.dao.CrmSupplyMaterialUnitDao;
import com.sifang.modules.supply.setting.entity.CrmSupplyMaterialType;
import com.sifang.modules.supply.setting.entity.CrmSupplyMaterialUnit;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.LayuiPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CrmSupplyMaterialSettingService extends BaseService {


    @Autowired
    private CrmSupplyMaterialTypeDao materialTypeDao;

    @Autowired
    private CrmSupplyMaterialUnitDao materialUnitDao;

    private Logger logger = LoggerFactory.getLogger(getClass());
    public LayuiPage materialTypeList(LayuiPage page, Map<String, String> map) {
        List<Record> list = materialTypeDao.materialTypeList(page, map);
        page.setData(list);
        page.setCount(materialTypeDao.materialTypeListCount(map));
        return page;
    }

    public void saveMaterialType(String name, String attribute, String id) {
        if (materialTypeDao.checkName(name, id)) {
            throw new BusinessException("物料类型已存在，请勿重复添加!");
        }
        if (!StringUtil.equalsAny(attribute, "0", "1")) {
            throw new BusinessException("物料属性格式不正确");
        }
        Date date = new Date();
        User user = UserUtils.getUser();
        CrmSupplyMaterialType materialType;
        if (StringUtil.isBlank(id)) {
            materialType = new CrmSupplyMaterialType();
            materialType.setCreateTime(date);
            materialType.setCreateBy(user.getId());
        } else {
            materialType = materialTypeDao.get(id);
            materialType.setUpdateTime(date);
        }
        materialType.setName(name);
        materialType.setAttribute(attribute);
        materialTypeDao.save(materialType);
    }

    public void deleteMaterialType(String ids) {
        Db.update("UPDATE `crm_supply_material_type` SET STATUS='2',update_time=NOW() WHERE id in (" + StringUtil.joinInSql(ids.split(",")) + ")");
    }

    public CrmSupplyMaterialType getTypeDetai(String id) {
        CrmSupplyMaterialType materialType = materialTypeDao.get(id);
        return materialType;
    }


    public LayuiPage materialUnitList(LayuiPage page, Map<String, String> map) {
        List<Record> list = materialUnitDao.materialUnitList(page, map);
        page.setData(list);
        page.setCount(materialUnitDao.materialUnitListCount(map));
        return page;
    }

    public CrmSupplyMaterialUnit getUnitDetail(String id){
        CrmSupplyMaterialUnit materialUnit=materialUnitDao.get(id);
        return materialUnit;
    }

    public void deleteMaterialUnit(String ids) {
        Db.update("UPDATE `crm_supply_material_unit` SET STATUS='2',update_time=NOW() WHERE id in (" + StringUtil.joinInSql(ids.split(",")) + ")");
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveMaterialUnit(String name, String id,String materialType,String unitCode,String UnitGroup){
//        if (materialUnitDao.checkName(unitCode, id)) {
//            throw new BusinessException("库存单位已存在，请勿重复添加!");
//        }
        Date date = new Date();
        User user = UserUtils.getUser();
        CrmSupplyMaterialUnit materialUnit;
        if (StringUtil.isBlank(id)) {
            if (StringUtil.isBlank(unitCode)) {
                unitCode = materialUnitDao.newUnitCode();
            }
            materialUnit = new CrmSupplyMaterialUnit();
            materialUnit.setCreateTime(date);
            materialUnit.setCreateBy(user.getId());
            materialUnit.setUnitCode(unitCode);
            materialUnit.setUnitGroup(UnitGroup);
            materialUnit.setMaterialType(materialType);
            materialUnit.setName(name);
           // TSUnit(materialUnit);
        } else {
            materialUnit = materialUnitDao.get(id);
            materialUnit.setUnitGroup(UnitGroup);
            materialUnit.setMaterialType(materialType);
            materialUnit.setName(name);
            materialUnit.setUpdateTime(date);
           // editUnit(materialUnit);

        }
        materialUnitDao.save(materialUnit);
    }
    /**
     * 推送金蝶数据
    */
    public  void TSUnit(CrmSupplyMaterialUnit materialUnit)  {
        try {
            Gson gson = new Gson();
            K3CloudApi client = new K3CloudApi();
            // 保存
            Map<String,Object> data=new HashMap<>();

            Map<String,Object> model=new HashMap<>();
            model.put("FName", materialUnit.getName());    //名称
            model.put("FNumber",materialUnit.getUnitCode());
            model.put("FRoundType", "四舍五入");    //仓库属性
            Map<String,Object> FUnitGroupId=new HashMap<>();
            FUnitGroupId.put("FNumber",materialUnit.getUnitGroup());
            model.put("FUnitGroupId",FUnitGroupId);
            data.put("Model", model);
            String json=gson.toJson(data);
            KingDeeResponseVo result= KingDeeUtil.kingDeeClitSave(json, KingDeeConstants.UNIT_CODE,gson,client);
            String id=result.getId();
            materialUnit.setKingDeeId(id);
            Map<String, Object> data2 = new HashMap<>();
            data2.put("Ids", id);
            String json2 = gson.toJson(data2);
            System.out.println(json2);
            KingDeeUtil.kingDeeClitSubmit(json2, KingDeeConstants.UNIT_CODE,gson,client);

            KingDeeUtil.kingDeeClitAudit(json2, KingDeeConstants.UNIT_CODE,gson,client);
        }catch (Exception e){
            logger.error("单位同步金蝶系统数据失败：{}",e);
            throw new BusinessException("单位同步金蝶系统失败");
        }
    }

    public void editUnit(CrmSupplyMaterialUnit materialUnit)  {
        try {
        logger.info(">>>>>>>>>>>推送金蝶系统 editUnit materialUnit:{}",materialUnit.getId());
        Map<String, Object> data1 = new HashMap<>();
        data1.put("Ids", materialUnit.getKingDeeId());

        Gson gson = new Gson();
        K3CloudApi client = new K3CloudApi();
        String json1 = gson.toJson(data1);
        //反审核
        KingDeeUtil.kingDeeClitUnAudit(json1,KingDeeConstants.UNIT_CODE,gson,client);

        Map<String,Object> data=new HashMap<>();

        Map<String,Object> model=new HashMap<>();
            model.put("FUNITID", materialUnit.getKingDeeId());
            model.put("FName", materialUnit.getName());    //名称
        model.put("FNumber",materialUnit.getUnitCode());
        model.put("FRoundType", "四舍五入");    //仓库属性
        Map<String,Object> FUnitGroupId=new HashMap<>();
        FUnitGroupId.put("FNumber",materialUnit.getUnitGroup());
        model.put("FUnitGroupId",FUnitGroupId);
        data.put("Model", model);
        String json=gson.toJson(data);
        //保存
        KingDeeResponseVo result= KingDeeUtil.kingDeeClitSave(json, KingDeeConstants.UNIT_CODE,gson,client);

        Map<String, Object> data2 = new HashMap<>();
        data2.put("Ids",result.getId());
        String json2 = gson.toJson(data2);
        //提交
        KingDeeUtil.kingDeeClitSubmit(json2, KingDeeConstants.UNIT_CODE,gson,client);
        //审核
        KingDeeUtil.kingDeeClitAudit(json2, KingDeeConstants.UNIT_CODE,gson,client);
        }catch (Exception e){
            logger.error("单位同步修改金蝶系统数据失败：{}",e);
            throw new BusinessException("单位同步修改金蝶系统数据失败");
        }
    }
    /**
     * 物料类型 下拉选
     */
    public List<Record> listMaterielType() {
        return materialTypeDao.listMaterielType();
    }

    public List<Record> listMaterialUnit(String typeId){
        return materialUnitDao.listMaterialUnit(typeId);
    }
}
