package com.xtd.framework.web.controller;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.xtd.common.utils.SecurityUtils;
import com.xtd.common.utils.http.HKHttpUtil;
import com.xtd.project.system.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xtd.common.constant.HttpStatus;
import com.xtd.common.utils.DateUtils;
import com.xtd.common.utils.StringUtils;
import com.xtd.common.utils.sql.SqlUtil;
import com.xtd.framework.web.domain.AjaxResult;
import com.xtd.framework.web.page.PageDomain;
import com.xtd.framework.web.page.TableDataInfo;
import com.xtd.framework.web.page.TableSupport;

/**
 * web层通用数据处理
 * 
 * @author xtd
 */
public class BaseController
{
    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
        {
            @Override
            public void setAsText(String text)
            {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 响应返回结果
     * 
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows)
    {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Value("${artemisconfig.openapi.path}")
    public String OPENAPI_PATH;
    @Value("${artemisconfig.host}")
    public String ARTEMISCONFIG_HOST;
    @Value("${artemisconfig.appKey}")
    public String ARTEMISCONFIG_APPKEY;
    @Value("${artemisconfig.appSecret}")
    public String ARTEMISCONFIG_APPSECRET;

    //平台地址，钥匙，密钥配置
    public void HKConn() {
        System.out.println(ARTEMISCONFIG_HOST +";" + ARTEMISCONFIG_APPKEY + ";" + ARTEMISCONFIG_APPSECRET);
        ArtemisConfig.host = ARTEMISCONFIG_HOST;
        ArtemisConfig.appKey = ARTEMISCONFIG_APPKEY;
        ArtemisConfig.appSecret = ARTEMISCONFIG_APPSECRET;
    }

    /**
     * post请求查询
     * @param url 路径
     * @param body 条件参数
     * @param querys
     * @param accept
     * @param contentType 数据类型
     * @return
     */
    protected Object postSelect(String url, String body, Map<String, String> querys, String accept, String contentType){
        HKConn();

        //调用接口
        String result = HKHttpUtil.post(OPENAPI_PATH + url,body,null,null,null);

        logger.info(result);
        if (result != null){
            return resultObject(result);
        }
        return null;
    }

    /**
     * post指令
     * @param url
     * @param body
     * @param querys
     * @param accept
     * @param contentType
     * @return
     */
    protected Object postAction(String url, String body, Map<String, String> querys, String accept, String contentType){
        HKConn();

        //调用接口
        String result = HKHttpUtil.post(OPENAPI_PATH + url,body,null,null,null);

        logger.info(result);
        if (result != null){
            JSONObject object = JSONObject.parseObject(result);
            if (object != null && "0".equals(object.get("code"))){
                if(object.get("data") != null && object.get("data") != ""){
                    return object.get("data");
                }
                return object.get("msg");
            }
        }
        return null;
    }

    /**
 * 调用接口返回信息
 *
 * @param result
 * @return
 */
    protected  Map<String,Object> resultObject(String result){
        logger.info(result);
        JSONObject object = JSONObject.parseObject(result);
        Map<String,Object> map = new HashMap<>();
        if (object != null && "0".equals(object.get("code"))){
            JSONObject dataObject = (JSONObject) object.get("data");
            if (dataObject.containsKey("list")){ //列表
                Integer total = Integer.parseInt(dataObject.get("total").toString());
                map.put("total",total);
                map.put("list",dataObject.get("list"));
                return map;
            }

            map.put("object",dataObject);
        }

        return null;
    }

    protected void setPage(Map<String,Object> params,Integer pageNo,Integer pageSize){
        if (pageNo == null || pageNo == 0){
            pageNo = 1;
        }
        if (pageSize == null){
            pageSize = 500;
        }
        params.put("pageNo",String.valueOf(pageNo));
        params.put("pageSize",String.valueOf(pageSize));
    }

    /**
     * 当前登录用户
     * @return
     */
    protected SysUser getUser(){
        return SecurityUtils.getLoginUser().getUser();
    }

    /**
     * 当前登录用户id
     * @return
     */
    protected String getUserId(){
        return String.valueOf(getUser().getUserId());
    }

    /**
     * 当前登录用户组织id
     * @return
     */
    protected String getDeptId(){
        return String.valueOf(getUser().getDeptId());
    }

}
