package com.chinaitop.depot.intelligent.basicdata.controller;

import com.chinaitop.depot.intelligent.basicdata.model.BasicStorehouse;
import com.chinaitop.depot.intelligent.basicdata.model.OrgInfo;
import com.chinaitop.depot.intelligent.basicdata.service.WareHouseBasicInfoService;
import com.chinaitop.depot.intelligent.utils.DateUtils;
import com.chinaitop.depot.intelligent.utils.JsonToObjectUtils;
import com.chinaitop.depot.intelligent.wsClient.WebServiceSer;
import com.chinaitop.depot.intelligent.wsClient.WebServiceSerSoap;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.unissoft.model.ResponseEntity;
import com.unissoft.model.SendEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qingsong.han
 * @description: 查询data_kcgl_kcsw_default和basic_storehouse
 * 获取基本信息
 * @create 2018-12-17 14:01
 */
@RestController
@RequestMapping(value = "/intelligents/wareHouseBasicInfo")
@Api(value = "WareHouseBasicInfoController", description = "仓房基础信息控制类")
@SuppressWarnings("all")
public class WareHouseBasicInfoController {

    @Resource
    private WareHouseBasicInfoService wareHouseBasicInfoService;

    /**
     * 根据单位查找单位下的所有仓房信息(统一对外接口)
     *
     * @param unitId 单位ID
     * @return
     */
    @RequestMapping(value = "/getWareHouseInfo", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    @ApiOperation(value = "根据单位查找单位下的所有仓房信息(统一对外接口)", notes = "根据单位查找单位下的所有仓房信息(统一对外接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "unitId", value = "单位ID", paramType = "query"),
            @ApiImplicitParam(name = "libraryType", value = "仓房性质(主粮库或代储点)", paramType = "query")
    })
    public Map<String, Object> getStorehouseList(Integer unitId, String libraryType) {
        Map<String, Object> map = wareHouseBasicInfoService.getStorehouseInfo(unitId, libraryType);
        return map;
    }

    /**
     * 库点信息推送到智远
     *
     * @param orgInfoJson              推送库点信息json字符串
     * @param CUD:Create,Update,Delete 标识: 新增("I"),删除("D"),修改("U")
     * @return
     */
    @RequestMapping(value = "/saveGrainpoint", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    @ApiOperation(value = "推送库点信息", notes = "推送库点信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgInfoJson", value = "库点数据", paramType = "form"),
            @ApiImplicitParam(name = "CUD", value = "库点数据:新增(I),删除(D),修改(U)", paramType = "query")
    })
    public ResponseEntity saveGrainpoint(String orgInfoJson, String CUD) {
        // 非空判断
        if (StringUtils.isNotBlank(orgInfoJson)) {
            if (StringUtils.isNotBlank(CUD)) {
                // json转对象
                OrgInfo orgInfo = (OrgInfo) JsonToObjectUtils.jsonToObject(orgInfoJson, OrgInfo.class);
                // 封装推送数据
                Map<String, Object> orgInfoMap = new HashMap<>();
                orgInfoMap.put("vKdCode", orgInfo.getOrgId()); // 库点编码
                orgInfoMap.put("vKdName", orgInfo.getOrgName()); // 库点名称
                orgInfoMap.put("vKdShort", orgInfo.getShortName()); // 库点简称
                orgInfoMap.put("vKdQyxz", orgInfo.getCompanyNature()); // 企业性质
                orgInfoMap.put("vKdType", orgInfo.getBusiType()); // 企业类型
                orgInfoMap.put("vBuildDate", DateUtils.formatDate(orgInfo.getCompleteDate() == null ? new Date() : orgInfo.getCompleteDate())); // 建造日期
                orgInfoMap.put("fcapacity", orgInfo.getEffectiveCapacity()); // 容量
                orgInfoMap.put("vTelephone", orgInfo.getContact()); // 电话
                orgInfoMap.put("vFax", orgInfo.getFax()); // 传真
                orgInfoMap.put("vKdaddress", orgInfo.getAddress()); // 地址
                orgInfoMap.put("vPostCode", orgInfo.getPost()); // 邮件代码
                orgInfoMap.put("vPerson", orgInfo.getLegalPerson());// 法人
                orgInfoMap.put("fKdArea", orgInfo.getDepotArea()); // 库点面积
                orgInfoMap.put("province", orgInfo.getProvince()); // 省
                orgInfoMap.put("city", orgInfo.getCity()); // 市
                orgInfoMap.put("province2", null); // 省2
                // 封装推送数据为数组格式
                ArrayList<SendEntity> tGrainpoints = null;
                // 判断推送数据操作insert,delete,update
                if ("I".equals(CUD)) { // 新增(I)
                    tGrainpoints = Lists.newArrayList(SendEntity.insertConvert(orgInfoMap));
                } else if ("D".equals(CUD)) { // 删除
                    tGrainpoints = Lists.newArrayList(SendEntity.deleteConvert(orgInfoMap));
                } else if ("U".equals(CUD)) { // 更新
                    tGrainpoints = Lists.newArrayList(SendEntity.updateConvert(orgInfoMap));
                }
                try {
                    // 创建json转换对象
                    ObjectMapper objectMapper = new ObjectMapper();
                    // 对象转json字符串
                    String jsonStr = objectMapper.writeValueAsString(tGrainpoints);
                    // webService对象
                    WebServiceSer webs = new WebServiceSer();
                    // 获取cxf代理
                    WebServiceSerSoap factor = webs.getWebServiceSerSoap();
                    // 推送数据并返回结果
                    String s = factor.saveGrainPointData(jsonStr);
                    // 返回结果给调用接口
                    return ResponseEntity.ok(s);
                } catch (Exception e) {
                    e.printStackTrace();
                    return ResponseEntity.failed("推送失败");
                }
            }
        }
        return null;

    }

    /**
     * 接口推送同步仓房信息设置
     *
     * @param basicStorehouseJson 字符串格式json数据
     * @param del                 删除标识(值: D)
     * @return
     */
    @RequestMapping(value = "/synchronizationStoreHouse", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
    @ApiOperation(value = "推送仓房信息", notes = "推送仓房信息数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "basicStorehouseJson", value = "仓房信息数据", paramType = "form"),
            @ApiImplicitParam(name = "del", defaultValue = "D", value = "删除标识", paramType = "query")
    })
    public ResponseEntity synchronizationStoreHouse(String basicStorehouseJson, String del) {
        // 非空判断
        if (StringUtils.isNotBlank(basicStorehouseJson)) {
            // json转对象
            BasicStorehouse storehouse = (BasicStorehouse) JsonToObjectUtils.jsonToObject(basicStorehouseJson, BasicStorehouse.class);
            // 封装推送数据
            Map<String, Object> wareHouseData = new HashMap<>();
            wareHouseData.put("vKdCode", storehouse.getOrgId()); // 库点id
            wareHouseData.put("vCfCode", storehouse.getStorehouseCode()); // 仓房编码
            wareHouseData.put("vCfName", storehouse.getStorehouseName()); // 仓房名称
            wareHouseData.put("vCfType", storehouse.getStorehouseType()); // 仓房类型编号
            wareHouseData.put("vCfStruct", null); // 仓房结构
            wareHouseData.put("vBuildType", storehouse.getArchitectureType()); // 建筑类型编号
            wareHouseData.put("vCfLong", storehouse.getLength()); // 仓内长
            wareHouseData.put("vCfWide", storehouse.getWidth()); // 仓内宽
            wareHouseData.put("vCfHigh", storehouse.getHeigth()); // 仓内高
            wareHouseData.put("fDesignCap", storehouse.getDesignCapacity()); // 设计仓容
            wareHouseData.put("fActCap", null); //
            wareHouseData.put("vWorkDate", DateUtils.formatDate(storehouse.getUsedate() == null ? new Date() : storehouse.getUsedate())); // 启用日期
            wareHouseData.put("vCfStatus", null);
            wareHouseData.put("vRemark", storehouse.getStorehouseState());
            wareHouseData.put("vKeeperId", storehouse.getDutystoreman()); // 保管员
            wareHouseData.put("duiliangH", storehouse.getGrainLineHeigth()); // 装粮线高
            wareHouseData.put("isshuliangjiace", null); // 是否启用数量检测功能 1 启用
            wareHouseData.put("isInCheck", null); // 是否在检查 1代表是 0或null代表不是
            wareHouseData.put("checkMode", null); // 检查模式 标准或者快速
            wareHouseData.put("isWzc", null);
            wareHouseData.put("type", null);
            wareHouseData.put("id", null);
            // 封装推送数据为数组格式
            ArrayList<SendEntity> wareHouses = null;
            // 判断推送数据操作insert,delete,update
            if (storehouse.getStorehouseId() == null) {
                // 插入
                wareHouses = Lists.newArrayList(SendEntity.insertConvert(wareHouseData));
            } else if (StringUtils.isNotBlank(del) && "D".equals(del)) {
                // 删除
                wareHouses = Lists.newArrayList(SendEntity.deleteConvert(wareHouseData));
            } else {
                // 更新
                wareHouses = Lists.newArrayList(SendEntity.updateConvert(wareHouseData));
            }
            try {
                // 创建json转换对象
                ObjectMapper objectMapper = new ObjectMapper();
                // 对象转json字符串
                String jsonStr = objectMapper.writeValueAsString(wareHouses);
                // webService对象
                WebServiceSer webs = new WebServiceSer();
                // 获取cxf代理
                WebServiceSerSoap factor = webs.getWebServiceSerSoap();
                // 推送数据并返回结果
                String s = factor.saveWareHouseData(jsonStr);
                // 返回结果给调用接口
                return ResponseEntity.ok(s);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseEntity.failed("推送失败");
            }
        }
        return null;
    }

    @RequestMapping(value = "/getStorehouse", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    @ApiOperation(value = "根据单位和仓房code查询仓房信息(统一对外接口)", notes = "根据单位和仓房code查询仓房信息(统一对外接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "单位编码", paramType = "query"),
            @ApiImplicitParam(name = "cfCode", value = "仓房code", paramType = "query"),
            @ApiImplicitParam(name = "libraryType", value = "仓房性质(主粮库或代储点)", paramType = "query")
    })
    public ResponseEntity getStorehouse(Integer orgId, String libraryType,String cfCode) {
        Map<String, Object> map = null;
        try {
            map = wareHouseBasicInfoService.getStorehouse(orgId, libraryType,cfCode);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.failed("查询仓房信息失败");
        }
        return ResponseEntity.ok(map);
    }
}
